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?
import java.io.*;
private void stringToFile( String text, String fileName )
{
try
{
File file = new File( fileName );
// if file doesnt exists, then create it
if ( ! file.exists( ) )
{
file.createNewFile( );
}
FileWriter fw = new FileWriter( file.getAbsoluteFile( ) );
BufferedWriter bw = new BufferedWriter( fw );
bw.write( text );
bw.close( );
//System.out.println("Done writing to " + fileName); //For testing
}
catch( IOException e )
{
System.out.println("Error: " + e);
e.printStackTrace( );
}
} //End method stringToFile
You can insert this method into your classes. If you are using this method in a class with a main method, change this class to static by adding the static key word. Either way you will need to import java.io.* to make it work otherwise File, FileWriter and BufferedWriter will not be recognized.
Basically the same answer as here, but easy to copy/paste, and it just works ;-)
import java.io.FileWriter;
public void saveToFile(String data, String filename) {
try (
FileWriter fw = new FileWriter(filename)) {
fw.write(data);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
It's better to close the writer/outputstream in a finally block, just in case something happen
finally{
if(writer != null){
try{
writer.flush();
writer.close();
}
catch(IOException ioe){
ioe.printStackTrace();
}
}
}
My way is based on stream due to running on all Android versions and needs of fecthing resources such as URL/URI, any suggestion is welcome.
As far as concerned, streams (InputStream and OutputStream) transfer binary data, when developer goes to write a string to a stream, must first convert it to bytes, or in other words encode it.
public boolean writeStringToFile(File file, String string, Charset charset) {
if (file == null) return false;
if (string == null) return false;
return writeBytesToFile(file, string.getBytes((charset == null) ? DEFAULT_CHARSET:charset));
}
public boolean writeBytesToFile(File file, byte[] data) {
if (file == null) return false;
if (data == null) return false;
FileOutputStream fos;
BufferedOutputStream bos;
try {
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(data, 0, data.length);
bos.flush();
bos.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
Logger.e("!!! IOException");
return false;
}
return true;
}
You could do this:
import java.io.*;
import java.util.*;
class WriteText
{
public static void main(String[] args)
{
try {
String text = "Your sample content to save in a text file.";
BufferedWriter out = new BufferedWriter(new FileWriter("sample.txt"));
out.write(text);
out.close();
}
catch (IOException e)
{
System.out.println("Exception ");
}
return ;
}
};
In case if you need create text file based on one single string:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public class StringWriteSample {
public static void main(String[] args) {
String text = "This is text to be saved in file";
try {
Files.write(Paths.get("my-file.txt"), text.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
}
}