November 23, 2019

Read/write text file line by line in Java

  November 23, 2019
What if our data is not stored in a format oriented file types like Excel,Json or XML ?
There should be a way to read content from a normal text file line by line.

Below methods help us read/write data to .txt file in a line by line manner

Write to text file

Below method helps us to write each input to next line by passing the file path and the string to write as parameters.
It also creates the file if it already does't exist in the target location.

 public void fnWriteToTextFile(String sFilePath, String sText) {
  try {
   File file = new File(sFilePath);
   if (!file.exists()) {
    file.createNewFile();
   }

   FileWriter fw = new FileWriter(file, true);
   PrintWriter out = new PrintWriter(fw);

   // write to next line
   out.println(sText);

   // Close the file.
   out.close();

  } catch (IOException e) {
   System.out.println(e.getMessage());
  }
 }

Read from text file line by line

Now lets checkout how can we read the contents of the text file in a line by line manner and extract it of List of string. For this we need to pass the path of the file to read as a parameter.

 public ArrayList<String> fnReadLineByLine(String sFilePath) {

  ArrayList<String> data = new ArrayList<String>();

  try {
   File fileRead = new File(sFilePath);

   FileReader fileReadObj = new FileReader(fileRead);

   BufferedReader bufferedReader = new BufferedReader(fileReadObj);
   String line = bufferedReader.readLine();
   while (line != null) {
    data.add(line);
    // read next line
    line = bufferedReader.readLine();
   }

   fileReadObj.close();

  } catch (Exception e) {

  }
  return data;
 }

Delete a file if already exists

Sometimes there comes a scenario where we needs to delete the already existing instead of appending data to it.
We can use below code for those kind of situations.


 public void fnDeleteTextFile(String sFilePath) {
  File file = new File(sFilePath);
  if (file.exists()) {
   file.delete();
  }
 }
logoblog

Thanks for reading Read/write text file line by line in Java

Previous
« Prev Post

No comments:

Post a Comment

Bookmark this website for more workarounds and issue fixes.

Verify Zip file contents without extracting using C# + Selenium

While doing automation testing, we may get a scenario where we need to download a zip file and to validate the contents inside it. One way t...