Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to write String to file using java nio

I need to write(append) huge string to flat file using java nio. The encoding is ISO-8859-1.

Currently we are writing as shown below. Is there any better way to do the same ?

public void writeToFile(Long limit) throws IOException{      String fileName = "/xyz/test.txt";      File file = new File(fileName);              FileOutputStream fileOutputStream = new FileOutputStream(file, true);        FileChannel fileChannel = fileOutputStream.getChannel();      ByteBuffer byteBuffer = null;      String messageToWrite = null;      for(int i=1; i<limit; i++){          //messageToWrite = get String Data From database          byteBuffer = ByteBuffer.wrap(messageToWrite.getBytes(Charset.forName("ISO-8859-1")));          fileChannel.write(byteBuffer);               }      fileChannel.close(); } 

EDIT: Tried both options. Following are the results.

@Test public void testWritingStringToFile() {     DiagnosticLogControlManagerImpl diagnosticLogControlManagerImpl = new DiagnosticLogControlManagerImpl();     try {         File file = diagnosticLogControlManagerImpl.createFile();         long startTime = System.currentTimeMillis();         writeToFileNIOWay(file);         //writeToFileIOWay(file);         long endTime = System.currentTimeMillis();         System.out.println("Total Time is  " + (endTime - startTime));     } catch (IOException e) {         // TODO Auto-generated catch block         e.printStackTrace();     } }  /**  *  * @param limit  *            Long  * @throws IOException  *             IOException  */ public void writeToFileNIOWay(File file) throws IOException {     FileOutputStream fileOutputStream = new FileOutputStream(file, true);     FileChannel fileChannel = fileOutputStream.getChannel();     ByteBuffer byteBuffer = null;     String messageToWrite = null;     for (int i = 1; i < 1000000; i++) {         messageToWrite = "This is a test üüüüüüööööö";         byteBuffer = ByteBuffer.wrap(messageToWrite.getBytes(Charset             .forName("ISO-8859-1")));         fileChannel.write(byteBuffer);     } }  /**  *  * @param limit  *            Long  * @throws IOException  *             IOException  */ public void writeToFileIOWay(File file) throws IOException {     FileOutputStream fileOutputStream = new FileOutputStream(file, true);     BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(         fileOutputStream, 128 * 100);     String messageToWrite = null;     for (int i = 1; i < 1000000; i++) {         messageToWrite = "This is a test üüüüüüööööö";         bufferedOutputStream.write(messageToWrite.getBytes(Charset             .forName("ISO-8859-1")));     }     bufferedOutputStream.flush();     fileOutputStream.close(); }  private File createFile() throws IOException {     File file = new File(FILE_PATH + "test_sixth_one.txt");     file.createNewFile();     return file; } 

Using ByteBuffer and Channel: took 4402 ms

Using buffered Writer : Took 563 ms

like image 944
nobody Avatar asked Sep 09 '11 19:09

nobody


People also ask

What is the best way to write to a file in Java?

FileWriter: FileWriter is the simplest way to write a file in Java. It provides overloaded write method to write int, byte array, and String to the File. You can also write part of the String or byte array using FileWriter. FileWriter writes directly into Files and should be used only when the number of writes is less.


Video Answer


1 Answers

UPDATED:

Since Java11 there is a specific method to write strings using java.nio.file.Files:

Files.writeString(Paths.get(file.toURI()), "My string to save"); 

We can also customize the writing with:

Files.writeString(Paths.get(file.toURI()),                    "My string to save",                     StandardCharsets.UTF_8,                    StandardOpenOption.CREATE,                    StandardOpenOption.TRUNCATE_EXISTING); 

ORIGINAL ANSWER:

There is a one-line solution, using Java nio:

java.nio.file.Files.write(Paths.get(file.toURI()),                            "My string to save".getBytes(StandardCharsets.UTF_8),                           StandardOpenOption.CREATE,                           StandardOpenOption.TRUNCATE_EXISTING); 

I have not benchmarked this solution with the others, but using the built-in implementation for open-write-close file should be fast and the code is quite small.

like image 71
Roberto Avatar answered Sep 27 '22 19:09

Roberto