0
public static void main(String args[]) {
        decode E = new decode();
        String input = "apple";
       encode output  = E.compute(input);
        System.out.println("input decoded :" +E.d_decode(output))
}

Hi, I want the output to be printed in a file instead of printing it to the console. How do I do that? And I want the file to be created at the run time.I mean I am not adding the output to the already created file

Please be patient as I am new to java

2
  • Duplicate of stackoverflow.com/questions/2885173/… Commented Mar 1, 2019 at 17:51
  • Do you mean you want to write the content to file or you want to use a logger to write it to a log file? Commented Mar 1, 2019 at 21:23

1 Answer 1

1

You may use java.nio.file.Files which is available from Java 7 to write contents to a file in runtime. The file will be created if you give a correct path also you can set the preferred encoding.

JAVA 7+

Edited after suggestion of @Ivan

You may use PrintWriter, BufferedWriter, FileUtils etc. there are many ways. I am sharing an example with Files

String encodedString = "some higly secret text";
Path filePath = Paths.get("file.txt");
try {
    Files.write(filePath, encodedString, Charset.forName("UTF-8"));
} catch (IOException e) {
    e.printStackTrace();
    System.out.println("unable to write to file, reason"+e.getMessage());
}

To write multiple lines

List<String> linesToWrite = new ArrayList<>();
linesToWrite.add("encodedString 1");
linesToWrite.add("encodedString 2");
linesToWrite.add("encodedString 3");
Path filePath = Paths.get("file.txt");
try {
    Files.write(filePath, linesToWrite, Charset.forName("UTF-8"));
} catch (IOException e) {
    e.printStackTrace();
    System.out.println("unable to write to file, reason"+e.getMessage());
}

There are a million other ways but I think it would be good to start with because of its simplicity.

Before Java 7

PrintWriter writer = null;
String encodedString = "some higly secret 
try {
    writer = new PrintWriter("file.txt", "UTF-8");
    writer.println(encodedString);
    // to write multiple: writer.println("new line")
} catch (FileNotFoundException | UnsupportedEncodingException e) {
    e.printStackTrace();
}  finally {
    writer.close();
}
Sign up to request clarification or add additional context in comments.

1 Comment

It might not be obvious from your answer but option with PrintWriter will also work in Java 7 and 8.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.