简体   繁体   中英

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)

Open file in append mode.

make it

dos = new DataOutputStream(new FileOutputStream(outFile),true);

将构造函数FileOutputStream(File file, boolean append)与append = true一起使用

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM