In Java, I have text from a text field in a String variable called \"text\".
How can I save the contents of the \"text\" variable to a file?
Use FileUtils.writeStringToFile()
from Apache Commons IO. No need to reinvent this particular wheel.
Use this, it is very readable:
import java.nio.file.Files;
import java.nio.file.Paths;
Files.write(Paths.get(path), lines.getBytes(), StandardOpenOption.WRITE);
In Java 7 you can do this:
String content = "Hello File!";
String path = "C:/a.txt";
Files.write( Paths.get(path), content.getBytes());
There is more info here: http://www.drdobbs.com/jvm/java-se-7-new-file-io/231600403
Apache Commons IO contains some great methods for doing this, in particular FileUtils contains the following method:
static void writeStringToFile(File file, String data)
which allows you to write text to a file in one method call:
FileUtils.writeStringToFile(new File("test.txt"), "Hello File");
You might also want to consider specifying the encoding for the file as well.
Take a look at the Java File API
a quick example:
try (PrintStream out = new PrintStream(new FileOutputStream("filename.txt"))) {
out.print(text);
}
You can use the modify the code below to write your file from whatever class or function is handling the text. One wonders though why the world needs a new text editor...
import java.io.*;
public class Main {
public static void main(String[] args) {
try {
String str = "SomeMoreTextIsHere";
File newTextFile = new File("C:/thetextfile.txt");
FileWriter fw = new FileWriter(newTextFile);
fw.write(str);
fw.close();
} catch (IOException iox) {
//do stuff with exception
iox.printStackTrace();
}
}
}