Java @ Desk: File I/O | Java at your desk

BufferedWriter Append String to End of Existing File in Java

BufferedWriter Append String to End of Existing File in Java

java.io.BufferedWriter class is used to write string into a file in java.

With FileWriter, no need to check if File exists and no need to create the file.

The constructor takes the java.io.FileWriter object and creates the new file if the file does not exists.

There are two constructons for FileWriter class
1) FileWriter(file) - Content is over written
2) FileWriter(file, boolean append) - If append is true then content is appended

If boolean append is true, then the content is appended to the file else the content is over written

Its very important to call the flush() and close() method on the BufferedWriter otherwise contents will not be written to the file created.

To write using BufferedWriter following methods can be used :
1) write(String s) - It simply writes the String passed to this method
2) write(String s, int off, int len) - It writes the String from index off till len. If offset > 0 then len must be equal to len - off, otherwise it will throw java.lang.StringIndexOutOfBoundsException: String index out of range:

package test;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class BufferedWriterWrite {

 public static void main(String args[]) throws IOException {
  FileWriter fileWriter = null;
  BufferedWriter bufferedWriter = null;
  try {
   File file = new File("D:/kumar/Blogs/File Operations/write.txt");
   fileWriter = new FileWriter(file, true); // This will create new file if
            // it does not exists
   bufferedWriter = new BufferedWriter(fileWriter);
   String content = "Write this to file";
   bufferedWriter.write(content, 0, content.length());
  } catch (Exception cause) {
   cause.printStackTrace();
  } finally {
   bufferedWriter.flush();
   bufferedWriter.close();
   fileWriter.close();
  }
 }
}

BufferedWriter Write String into File in Java

BufferedWriter Write String into File in Java

java.io.BufferedWriter class is used to write string into a file in java.

With FileWriter, no need to check if File exists and no need to create the file.

The constructor takes the java.io.FileWriter object and creates the new file if the file does not exists.

Its very important to call the flush() and close() method on the BufferedWriter otherwise contents will not be written to the file created.

This implementation will over write the content in the file. If you want to append the content to end of existing file click BufferedWriter Append String to End of Existing File in Java

To write using BufferedWriter following methods can be used :
1) write(String s) - It simply writes the String passed to this method
2) write(String s, int off, int len) - It writes the String from index off till len. If offset > 0 then len must be equal to len - off, otherwise it will throw java.lang.StringIndexOutOfBoundsException: String index out of range:

package test;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class BufferedWriterWrite {

 public static void main(String args[]) throws IOException {
  FileWriter fileWriter = null;
  BufferedWriter bufferedWriter = null;
  try {
   File file = new File("D:/kumar/Blogs/File Operations/write.txt");
   fileWriter = new FileWriter(file); // This will create new file if
            // it does not exists
   bufferedWriter = new BufferedWriter(fileWriter);
   String content = "Write this to file";
   bufferedWriter.write(content, 0, content.length());
  } catch (Exception cause) {
   cause.printStackTrace();
  } finally {
   bufferedWriter.flush();
   bufferedWriter.close();
   fileWriter.close();
  }
 }
}

FileOutputStream Append String to End of Existing File in Java

FileOutputStream Append String to End of Existing File in Java

java.io.FileOutputStream class is used to write string into a file in java. If the file does not exists at the path provided, FileOutputStream class first creates the new file.

With FileOutputStream, no need to check if File exists and no need to create the file.

The constructor takes the java.io.File object and creates the new file.

There are two constructons for FileWriter class
1) FileOutputStream(file) - Content is over written
2) FileOutputStream(file, boolean append) - If append is true then content is appended

If boolean append is true, then the content is appended to the file else the content is over written

Its very important to call the close() method on the FileOutputStream otherwise contents will not be written to the file created.

The difference between FileWriter to write into File and FileOutputStream is FileWriter write() method takes String content whereas FileOutputStream write() method takes bytes to write the content to file.

To convert String to bytes, use getBytes() method of String class

package test;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileOutputStreamWrite {
 public static void main(String args[]) throws IOException {
  FileOutputStream fileOutputStream = null;
  try {
   File file = new File("D:/kumar/Blogs/File Operations/write.txt");
   fileOutputStream = new FileOutputStream(file, true);
   fileOutputStream.write("Write these bytes to file".getBytes());
  } catch (Exception cause) {
   cause.printStackTrace();
  } finally {
   fileOutputStream.flush();
   fileOutputStream.close();
  }
 }
}

FileWriter Append String to End of Existing File in Java

FileWriter Append String to End of Existing File in Java

java.io.FileWriter class is used to write string into a file in java. If the file does not exists at the path provided, FileWriter class first creates the new file.

With FileWriter, no need to check if File exists and no need to create the file.

The constructor takes the java.io.File object and creates the new file.

There are two constructons for FileWriter class
1) FileWriter(file) - Content is over written
2) FileWriter(file, boolean append) - If append is true then content is appended

If boolean append is true, then the content is appended to the file else the content is over written

Its very important to call the close() method on the FileWriter otherwise contents will not be written to the file created.

Client Code -

package test;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class FileWriterAppendWrite {

 public static void main(String args[]) throws IOException {
  FileWriter fileWriter = null;
  try {
   File file = new File("D:/kumar/Blogs/File Operations/write.txt");
   fileWriter = new FileWriter(file, true); // This will append the content to file
   fileWriter.write("This is the appended text");
  } catch (Exception cause) {
   cause.printStackTrace();
  } finally {
   fileWriter.close();
  }
 }
}

FileOutputStream Write String into File in Java

FileOutputStream Write String into File in Java

java.io.FileOutputStream class is used to write string into a file in java. If the file does not exists at the path provided, FileOutputStream class first creates the new file.

With FileOutputStream, no need to check if File exists and no need to create the file.

The constructor takes the java.io.File object and creates the new file.

Its very important to call the close() method on the FileOutputStream otherwise contents will not be written to the file created.

The difference between FileWriter to write into File and FileOutputStream is FileWriter write() method takes String content whereas FileOutputStream write() method takes bytes to write the content to file.

To convert String to bytes, use getBytes() method of String class

This implementation will over write the content in the file. If you want to append the content to end of existing file click FileOutputStream Append String to End of Existing File in Java

Client code

package test;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileOutputStreamWrite {
 public static void main(String args[]) throws IOException {
  FileOutputStream fileOutputStream = null;
  try {
   File file = new File("D:/kumar/Blogs/File Operations/write.txt");
   fileOutputStream = new FileOutputStream(file);
   fileOutputStream.write("Write these bytes to file".getBytes());
  } catch (Exception cause) {
   cause.printStackTrace();
  } finally {
   fileOutputStream.flush();
   fileOutputStream.close();
  }
 }
}

FileWriter Write String into File in Java

FileWriter Write String into File in Java

java.io.FileWriter class is used to write string into a file in java. If the file does not exists at the path provided, FileWriter class first creates the new file.

With FileWriter, no need to check if File exists and no need to create the file.

The constructor takes the java.io.File object and creates the new file.

Its very important to call the close() method on the FileWriter otherwise contents will not be written to the file created.

This implementation will over write the content in the file. If you want to append the content to end of existing file click FileWriter Append String to End of Existing File in Java

Client Code -

package test;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class FileWriterWrite {

 public static void main(String args[]) throws IOException {
  FileWriter fileWriter = null;
  try {
   File file = new File("D:/kumar/Blogs/File Operations/write.txt");
   fileWriter = new FileWriter(file); // This will create new file if it does not exists
   fileWriter.write("Write this to file");
  } catch (Exception cause) {
   cause.printStackTrace();
  } finally {
   fileWriter.close();
  }
 }
}

How To Read Text File into String



How To Read Text File into String

We read a file in java using the java.io.BufferedReader class.

In the below example we will see how to read a file in java and convert the contents to String object.

File contains this string - Online Psychology Degree, Online Paralegal Degree, Insurances, Domain Names, Interior Design Degree, Bank Loans


package com.file;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadFileToString {
 public static void main(String[] args) throws IOException {

  BufferedReader bufferedReader = new BufferedReader(new FileReader("<FILE_PATH>"));
  String outputString = "";
  StringBuffer stringBuffer = new StringBuffer();

  while ((outputString = bufferedReader.readLine()) != null) {
   stringBuffer.append(outputString);
  }

  System.out.println(stringBuffer.toString());
 }
}


Also in Java 7, a utility method is provided which is quiet fast and efficient

byte[] encoded = Files.readAllBytes(Paths.get(path));
return encoding.decode(ByteBuffer.wrap(encoded)).toString();


Convert InputStream to String in Java

Convert InputStream to String in Java

In java, when we perform file operations like reading from a file using java.io.InputStream & java.io.FileInputStream, we pass a file object and the java.io.InputStream object gives us the input stream.

What if we want to convert this input stream and display to content on a web page or store it in a string for further utilization.

Here is a simple example to convert input stream to String

Input String - Degree education on ine, Buy Domain Name, Car Insurance, Online Accounting Degree

package com.file;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class InputStreamToString {
 public static void main(String[] args) throws IOException {
  
  String originalString = "Student Loan Consolidation Calculator, Car Insurance, " +
    "Home improvement loan rates";
  
  InputStream inputStream = new ByteArrayInputStream(originalString.getBytes());
  
  BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
  String outputString = "";
  StringBuffer stringBuffer = new StringBuffer();
  
  while ((outputString = bufferedReader.readLine()) != null) {
   stringBuffer.append(outputString);
  }
  
  System.out.println(stringBuffer.toString());
 }
}

Java File Delete and DeleteOnExit

Java File Delete and DeleteOnExit
To delete a file in java, following package is getting used
1) import java.io.File - To handle file operations
2) import java.io.IOException - To handle any exceptions occur during the directory operation

While creating a directory, following things need to be checked:
1) Check if the file exists using the exists() method. Not mandarory
2) Make a call to delete() method

There are two ways to delete a file in java
1) delete() - Returns true if the file gets deleted successfully. It deletes the file immediately as soon as the delete() method gets called
2) deleteOnExit() - The java.io.File.deleteOnExit() method deletes the file or directory defined by the abstract path name when the virtual machine terminates. It's purpose is to delete the file when the JVM exits.

Java Create Single Directory and Multiple Directories

Java Create Single Directory and Multiple Directories

To create a new directory in java, following package is getting used
1) import java.io.File - To handle file operations
2) import java.io.IOException - To handle any exceptions occur during the directory operation

While creating a directory, following things need to be checked:
1) The directory to be created, exists or not. It can be checked using the exists() method
2) If the above condition return false, the method mkdir() is called in order to create single directory.
3) If the above condition return false, the method mkdirs() is called in order to create multiple directories.

Java Create New File

Java Create New File

To create a new file in java, following package is getting used
1) import java.io.File - To handle file operations
2) import java.io.IOException - To handle any exceptions occur during the file operation

While creating a file, following things need to be checked:
1) The file to be created, exists or not. It can be checked using the exists() method
2) If the above condition return false, the method createNewFile() is called.