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

sith
  • 43
  • 1
  • 6
  • Duplicate of https://stackoverflow.com/questions/2885173/how-do-i-create-a-file-and-write-to-it-in-java – AndiCover Mar 01 '19 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? – Prasann Mar 01 '19 at 21:23

1 Answers1

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();
}
Van_Cleff
  • 842
  • 6
  • 14
  • 1
    It might not be obvious from your answer but option with `PrintWriter` will also work in Java 7 and 8. – Ivan Mar 01 '19 at 20:14