How do I save a String to a text file using Java? - java
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?
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.
Apache Commons IO contains some great methods for doing this, in particular FileUtils contains the following method:
static void writeStringToFile(File file, String data, Charset charset)
which allows you to write text to a file in one method call:
FileUtils.writeStringToFile(new File("test.txt"), "Hello File", Charset.forName("UTF-8"));
You might also want to consider specifying the encoding for the file as well.
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
Take a look at the Java File API
a quick example:
try (PrintStream out = new PrintStream(new FileOutputStream("filename.txt"))) {
out.print(text);
}
Just did something similar in my project. Use FileWriter will simplify part of your job. And here you can find nice tutorial.
BufferedWriter writer = null;
try
{
writer = new BufferedWriter( new FileWriter( yourfilename));
writer.write( yourstring);
}
catch ( IOException e)
{
}
finally
{
try
{
if ( writer != null)
writer.close( );
}
catch ( IOException e)
{
}
}
Use FileUtils.writeStringToFile() from Apache Commons IO. No need to reinvent this particular wheel.
In Java 11 the java.nio.file.Files class was extended by two new utility methods to write a string into a file. The first method (see JavaDoc here) uses the charset UTF-8 as default:
Files.writeString(Path.of("my", "path"), "My String");
And the second method (see JavaDoc here) allows to specify an individual charset:
Files.writeString(Path.of("my", "path"), "My String", StandardCharset.ISO_8859_1);
Both methods have an optional Varargs parameter for setting file handling options (see JavaDoc here). The following example would create a non-existing file or append the string to an existing one:
Files.writeString(Path.of("my", "path"), "String to append", StandardOpenOption.CREATE, StandardOpenOption.APPEND);
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();
}
}
}
I prefer to rely on libraries whenever possible for this sort of operation. This makes me less likely to accidentally omit an important step (like mistake wolfsnipes made above). Some libraries are suggested above, but my favorite for this kind of thing is Google Guava. Guava has a class called Files which works nicely for this task:
// This is where the file goes.
File destination = new File("file.txt");
// This line isn't needed, but is really useful
// if you're a beginner and don't know where your file is going to end up.
System.out.println(destination.getAbsolutePath());
try {
Files.write(text, destination, Charset.forName("UTF-8"));
} catch (IOException e) {
// Useful error handling here
}
Using Java 7:
public static void writeToFile(String text, String targetFilePath) throws IOException
{
Path targetPath = Paths.get(targetFilePath);
byte[] bytes = text.getBytes(StandardCharsets.UTF_8);
Files.write(targetPath, bytes, StandardOpenOption.CREATE);
}
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();
}
}
}
Use Apache Commons IO api. Its simple
Use API as
FileUtils.writeStringToFile(new File("FileNameToWrite.txt"), "stringToWrite");
Maven Dependency
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
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);
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.
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 ;
}
};
Using org.apache.commons.io.FileUtils:
FileUtils.writeStringToFile(new File("log.txt"), "my string", Charset.defaultCharset());
If you only care about pushing one block of text to file, this will overwrite it each time.
JFileChooser chooser = new JFileChooser();
int returnVal = chooser.showSaveDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
FileOutputStream stream = null;
PrintStream out = null;
try {
File file = chooser.getSelectedFile();
stream = new FileOutputStream(file);
String text = "Your String goes here";
out = new PrintStream(stream);
out.print(text); //This will overwrite existing contents
} catch (Exception ex) {
//do something
} finally {
try {
if(stream!=null) stream.close();
if(out!=null) out.close();
} catch (Exception ex) {
//do something
}
}
}
This example allows the user to select a file using a file chooser.
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);
}
}
private static void generateFile(String stringToWrite, String outputFile) {
try {
FileWriter writer = new FileWriter(outputFile);
writer.append(stringToWrite);
writer.flush();
writer.close();
log.debug("New File is generated ==>"+outputFile);
} catch (Exception exp) {
log.error("Exception in generateFile ", exp);
}
}
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();
}
}
}
I think the best way is using Files.write(Path path, Iterable<? extends CharSequence> lines, OpenOption... options):
String text = "content";
Path path = Paths.get("path", "to", "file");
Files.write(path, Arrays.asList(text));
See javadoc:
Write lines of text to a file. Each line is a char sequence and is
written to the file in sequence with each line terminated by the
platform's line separator, as defined by the system property
line.separator. Characters are encoded into bytes using the specified
charset.
The options parameter specifies how the the file is created or opened.
If no options are present then this method works as if the CREATE,
TRUNCATE_EXISTING, and WRITE options are present. In other words, it
opens the file for writing, creating the file if it doesn't exist, or
initially truncating an existing regular-file to a size of 0. The
method ensures that the file is closed when all lines have been
written (or an I/O error or other runtime exception is thrown). If an
I/O error occurs then it may do so after the file has created or
truncated, or after some bytes have been written to the file.
Please note. I see people have already answered with Java's built-in Files.write, but what's special in my answer which nobody seems to mention is the overloaded version of the method which takes an Iterable of CharSequence (i.e. String), instead of a byte[] array, thus text.getBytes() is not required, which is a bit cleaner I think.
If you wish to keep the carriage return characters from the string into a file
here is an code example:
jLabel1 = new JLabel("Enter SQL Statements or SQL Commands:");
orderButton = new JButton("Execute");
textArea = new JTextArea();
...
// String captured from JTextArea()
orderButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
// When Execute button is pressed
String tempQuery = textArea.getText();
tempQuery = tempQuery.replaceAll("\n", "\r\n");
try (PrintStream out = new PrintStream(new FileOutputStream("C:/Temp/tempQuery.sql"))) {
out.print(tempQuery);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(tempQuery);
}
});
I have published a library that saves files, and handles everything with one line of code only, you can find it here along with its documentation
Github repository
and the answer to your question is so easy
String path = FileSaver
.get()
.save(string.getBytes(),"file.txt");
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;
}
Related
Any explanation as to why Output Stream only prints the last line of the translated variable to a new file instead of all the lines?
I am trying to convert English words from a text file to a new file that translates the words into pig Latin. Everything translates the way it should when it is simply printed to the console but the issue I am having is that only the last line from the initial file appears on the new one. public static void newFile(String pigLatin) { OutputStream os = null; try { os = new FileOutputStream(new File("/Users/amie/Documents/inputnewnew.pig.txt")); os.write(pigLatin.getBytes(), 0, pigLatin.length()); } catch (IOException e) { e.printStackTrace(); } finally { try { os.close(); } catch (IOException e) { e.printStackTrace(); } } }
By default FileOutputStream is overriding the existing file. What you need to do is to use another constructor with append parameter FileOutputStream(String name, boolean append) like os = new FileOutputStream(new File("/Users/...", true)) Take a look at the reference
Save to text file [duplicate]
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?
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.
Apache Commons IO contains some great methods for doing this, in particular FileUtils contains the following method: static void writeStringToFile(File file, String data, Charset charset) which allows you to write text to a file in one method call: FileUtils.writeStringToFile(new File("test.txt"), "Hello File", Charset.forName("UTF-8")); You might also want to consider specifying the encoding for the file as well.
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
Take a look at the Java File API a quick example: try (PrintStream out = new PrintStream(new FileOutputStream("filename.txt"))) { out.print(text); }
Just did something similar in my project. Use FileWriter will simplify part of your job. And here you can find nice tutorial. BufferedWriter writer = null; try { writer = new BufferedWriter( new FileWriter( yourfilename)); writer.write( yourstring); } catch ( IOException e) { } finally { try { if ( writer != null) writer.close( ); } catch ( IOException e) { } }
Use FileUtils.writeStringToFile() from Apache Commons IO. No need to reinvent this particular wheel.
In Java 11 the java.nio.file.Files class was extended by two new utility methods to write a string into a file. The first method (see JavaDoc here) uses the charset UTF-8 as default: Files.writeString(Path.of("my", "path"), "My String"); And the second method (see JavaDoc here) allows to specify an individual charset: Files.writeString(Path.of("my", "path"), "My String", StandardCharset.ISO_8859_1); Both methods have an optional Varargs parameter for setting file handling options (see JavaDoc here). The following example would create a non-existing file or append the string to an existing one: Files.writeString(Path.of("my", "path"), "String to append", StandardOpenOption.CREATE, StandardOpenOption.APPEND);
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(); } } }
I prefer to rely on libraries whenever possible for this sort of operation. This makes me less likely to accidentally omit an important step (like mistake wolfsnipes made above). Some libraries are suggested above, but my favorite for this kind of thing is Google Guava. Guava has a class called Files which works nicely for this task: // This is where the file goes. File destination = new File("file.txt"); // This line isn't needed, but is really useful // if you're a beginner and don't know where your file is going to end up. System.out.println(destination.getAbsolutePath()); try { Files.write(text, destination, Charset.forName("UTF-8")); } catch (IOException e) { // Useful error handling here }
Using Java 7: public static void writeToFile(String text, String targetFilePath) throws IOException { Path targetPath = Paths.get(targetFilePath); byte[] bytes = text.getBytes(StandardCharsets.UTF_8); Files.write(targetPath, bytes, StandardOpenOption.CREATE); }
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(); } } }
Use Apache Commons IO api. Its simple Use API as FileUtils.writeStringToFile(new File("FileNameToWrite.txt"), "stringToWrite"); Maven Dependency <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency>
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);
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.
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 ; } };
Using org.apache.commons.io.FileUtils: FileUtils.writeStringToFile(new File("log.txt"), "my string", Charset.defaultCharset());
If you only care about pushing one block of text to file, this will overwrite it each time. JFileChooser chooser = new JFileChooser(); int returnVal = chooser.showSaveDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { FileOutputStream stream = null; PrintStream out = null; try { File file = chooser.getSelectedFile(); stream = new FileOutputStream(file); String text = "Your String goes here"; out = new PrintStream(stream); out.print(text); //This will overwrite existing contents } catch (Exception ex) { //do something } finally { try { if(stream!=null) stream.close(); if(out!=null) out.close(); } catch (Exception ex) { //do something } } } This example allows the user to select a file using a file chooser.
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); } }
private static void generateFile(String stringToWrite, String outputFile) { try { FileWriter writer = new FileWriter(outputFile); writer.append(stringToWrite); writer.flush(); writer.close(); log.debug("New File is generated ==>"+outputFile); } catch (Exception exp) { log.error("Exception in generateFile ", exp); } }
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(); } } }
I think the best way is using Files.write(Path path, Iterable<? extends CharSequence> lines, OpenOption... options): String text = "content"; Path path = Paths.get("path", "to", "file"); Files.write(path, Arrays.asList(text)); See javadoc: Write lines of text to a file. Each line is a char sequence and is written to the file in sequence with each line terminated by the platform's line separator, as defined by the system property line.separator. Characters are encoded into bytes using the specified charset. The options parameter specifies how the the file is created or opened. If no options are present then this method works as if the CREATE, TRUNCATE_EXISTING, and WRITE options are present. In other words, it opens the file for writing, creating the file if it doesn't exist, or initially truncating an existing regular-file to a size of 0. The method ensures that the file is closed when all lines have been written (or an I/O error or other runtime exception is thrown). If an I/O error occurs then it may do so after the file has created or truncated, or after some bytes have been written to the file. Please note. I see people have already answered with Java's built-in Files.write, but what's special in my answer which nobody seems to mention is the overloaded version of the method which takes an Iterable of CharSequence (i.e. String), instead of a byte[] array, thus text.getBytes() is not required, which is a bit cleaner I think.
If you wish to keep the carriage return characters from the string into a file here is an code example: jLabel1 = new JLabel("Enter SQL Statements or SQL Commands:"); orderButton = new JButton("Execute"); textArea = new JTextArea(); ... // String captured from JTextArea() orderButton.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent ae) { // When Execute button is pressed String tempQuery = textArea.getText(); tempQuery = tempQuery.replaceAll("\n", "\r\n"); try (PrintStream out = new PrintStream(new FileOutputStream("C:/Temp/tempQuery.sql"))) { out.print(tempQuery); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(tempQuery); } });
I have published a library that saves files, and handles everything with one line of code only, you can find it here along with its documentation Github repository and the answer to your question is so easy String path = FileSaver .get() .save(string.getBytes(),"file.txt");
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; }
java how open file to write
I want to write a file but mixture of 3 bellow feature. how? BufferedWriter , high volume data write needed can append to exist text file can set charset like "cp1256" How mix all these features to open write file?
What you would do first is, Initiate your BufferedWriter : ` String fileName = METHOD ARGUMENT, OR REGULAR STRING ("Output.txt"); BufferedWriter writer = null; try { File outFile = new File(fileName); writer = new BufferedWriter(new FileWriter(OUTPUT NAME OF THE FILE YOU ARE WRITING. , true)); writer.write(WHAT YOU WANT TO WRITE TO THE FILE); } catch (Exception e) { e.printStackTrace(); } finally { try { // Close the writer regardless of what happens... writer.close(); } catch (Exception e) { } Now to explain the code so I'm not just spoon feeding it to you. When we declare the BufferedWriter writer = null; , we are setting it to null so that we don't write anything without setting a Try/Catch Exception Handler around it. Once we are within our exception handled, we initiate a File called outFile. This will be the file we are outputting. The Argument we give it is the name of the file name. (A String Value such as, "Output.txt") NOTE: You MUST add the extension or else it won't work the way you are hoping it does. Next, when we reference our BufferedWriter again, we initiate a new one in the try/catch handler, and inside we initiate a FileWriter (What will be doing the writing to the file). We give it two arguments. The name of the Output File("Output.txt"), and we also supply a true argument. What this does is makes the File Appendable! When we write true, we are saying we want the file to be appendable. Finally, we write to the file, whatever it is you want to write. As for the third feature, I don't think that FileWriter's will allow you to choose the Character Encoding that you want to write with, so unless you aren't using UTF-8, then you may want to use a PrintWriter To do this, you would simply replace our `writer = new BufferedWriter(new FileWriter(OUTPUT NAME OF THE FILE YOU ARE WRITING. , true)); writer = new BufferedWriter(new PrintWriter(outputName, "UTF-8")); I THINK this should work, if not, please let me know, I'll find a working solution.
public class WriteFile { BufferedWriter out; public void openFile(String file){ try { out = new BufferedWriter(new FileWriter("data.txt")); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void writeInts(int[] ints){ try { for(int i : ints) out.write(i+" "); out.newLine(); out.flush(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void closeFile(){ try { if (out!=null)out.close(); } catch (IOException e) { } } } import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class Test { public static void main(String[] args) throws IOException { WriteFile wf = new WriteFile(); wf.openFile("test.txt"); wf.writeInts(new int[]{1,2,3,4,5}); wf.writeInts(new int[]{5,4,3,2,1}); wf.closeFile(); BufferedReader bf = new BufferedReader(new FileReader("test.txt")); System.out.println(bf.readLine()); System.out.println(bf.readLine()); } } Output: Line1: 1 2 3 4 5 Line2: 5 4 3 2 1
How to convert .txt files to multiline String in Android Java
I've been stuck on this for a couple of days, I just cant find a good method to open a .txt file. I need to convert it into a multiline string and set it as a textview. Can someone help me please? as for the file location, I'm using: String saveLoc = Environment.getExternalStorageDirectory()+"/My Documents/"; public String title; public String Ftype = ".txt"; (saveLoc+title+Ftype) //is the file location. I can normally read the data into a file input stream, but if I try and do anything with it I get loads of errors that wont let my app even run.
use Apache Commons IO FileUtils.readLines() readLines public static List readLines(File file, Charset encoding) throws IOException Reads the contents of a file line by line to a List of Strings. The file is always closed. Parameters: file - the file to read, must not be null encoding - the encoding to use, null means platform default Returns: the list of Strings representing each line in the file, never null Throws: IOException - in case of an I/O error Since: 2.3
private static String readFile(String path) throws IOException { FileInputStream stream = new FileInputStream(new File(path)); try { FileChannel fc = stream.getChannel(); MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size()); /* Instead of using default, pass in a decoder. */ return Charset.defaultCharset().decode(bb).toString(); } catch (IOException e) { e.printStackTrace(); } finally { stream.close(); } }
private String readTxt(){ InputStream inputStream = new FileInputStream("Text File Path Here"); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); int i; try { i = inputStream.read(); while (i != -1) { byteArrayOutputStream.write(i); i = inputStream.read(); } inputStream.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return byteArrayOutputStream.toString(); }
File Read and Write
I Have a code for writing into a file each time there is an entry into the textfield. but after the process, when an entry is made again the file is rewritten instead of continuing with the entries to the file, and so I lose the previous data. How do I rewrite to the existing one, so that later I get to read those data even after closing the app. The code for the write process is given : public boolean writeToFile(String dataLine) { dataLine = "\n" + dataLine; try { File outFile = new File(filepath); dos = new DataOutputStream(new FileOutputStream(outFile)); dos.writeBytes(dataLine); dos.close(); } catch (FileNotFoundException ex) { return (false); } catch (IOException ex) { return (false); } return (true); } Could anyone pls make changes to the code as necessary and post it to me.
The [Java API for FileOutputStream][1] states: public FileOutputStream(String name, boolean append) throws FileNotFoundException) Creates an output file stream to write to the file with the specified name. If the second argument is true, then bytes will be written to the end of the file rather than the beginning. A new FileDescriptor object is created to represent this file connection. So, your code should look like this: public boolean writeToFile(String dataLine) { dataLine = "\n" + dataLine; try { File outFile = new File(filepath); dos = new DataOutputStream(new FileOutputStream(outFile,true)); dos.writeBytes(dataLine); dos.close(); } catch (FileNotFoundException ex) { return (false); } catch (IOException ex) { return (false); } return (true); } [1]: http://download.oracle.com/javase/6/docs/api/java/io/FileOutputStream.html#FileOutputStream(java.lang.String, boolean)
Use the constructor FileOutputStream(File file, boolean append) with append = true
Open file in append mode. make it dos = new DataOutputStream(new FileOutputStream(outFile),true); Document
See [http://download.oracle.com/javase/6/docs/api/java/io/FileOutputStream.html#FileOutputStream(java.io.File, boolean)][1] Also note that you should probably use a FileWriter to write text. FileOutputStream is for binary data. [1]: http://download.oracle.com/javase/6/docs/api/java/io/FileOutputStream.html#FileOutputStream(java.io.File, boolean)