2715/store-string-inside-a-file-using-java
I have some value inside a String variable by the name 'text'. How can I save the value from this variable to a text file using JAVA ?
If you're simply outputting text, rather than any binary data, the following will work: PrintWriter out = new PrintWriter("filename.txt"); Then, write your String to it, just like you would to any output stream: out.println(text); You'll need exception handling, as ever. Be sure to call out.close() when you've finished writing. If you are using Java 7 or later, you can use the "try-with-resources statement" which will automatically close your PrintStream when you are done with it (ie exit the block) like so: try (PrintWriter out = new PrintWriter("filename.txt")) { out.println(text); } You will still need to explicitly throw the java.io.FileNotFoundException as before.
We can use Apache Commons IO. It has some great methods to do this.
static void writeStringToFile(File file, String data)
FileUtils.writeStringToFile(new File("test.txt"), "Hello File");
Hey, @Pooja, Before starting with anything you should ...READ MORE
If you're simply outputting text, rather than ...READ MORE
If you're looking for an alternative that ...READ MORE
We can find out the no. of ...READ MORE
try { final Path ...READ MORE
List<String> results = new ArrayList<String>(); File[] files = ...READ MORE
You can use Scanner class to read ...READ MORE
import java.io.File; import java.nio.file.Files; File file; // ...(file is initialised)... byte[] ...READ MORE
// File (or directory) with old name File ...READ MORE
Using nio we can check whether file ...READ MORE
OR
At least 1 upper-case and 1 lower-case letter
Minimum 8 characters and Maximum 50 characters
Already have an account? Sign in.