Hello Developer , I am going to read a .txt file which is having content/data separated by Pipe ( | )
For instance,it would look like below file-
PipeSeparatedFile.txt
C20 | Java | 25
C21 | Python | 26
So lets start with the key things-
1.If you want to store the contents , then it is better to create a Java Pojo class and save the content in fields. For instance i have created a Student class with below fields and storing the file contents in it.
2.Always give the correct file path so that file is read and processed.
3.Have the logic of reading the file contents in a separate method so that its readable and specific to function.
Below is the code for reading the .txt file
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
class Student{
private String fieldOne;
private String fieldTwo;
private int fieldThree;
public String getFieldOne() {
return fieldOne;
}
public void setFieldOne(String fieldOne) {
this.fieldOne = fieldOne;
}
public String getFieldTwo() {
return fieldTwo;
}
public void setFieldTwo(String fieldTwo) {
this.fieldTwo = fieldTwo;
}
public int getFieldThree() {
return fieldThree;
}
public void setFieldThree(int fieldThree) {
this.fieldThree = fieldThree;
}
}
public class readingFileWithPipeSeparators {
public static void main(String[] args) {
String filePath = "E://docs//PipeSeparatedFile.txt";
List<Student> listOfStudents = null; //new ArrayList<Student>();
File file = new File(filePath);
if(file.exists()) {
System.out.println("file exists");
try {
FileReader fileReader = new FileReader(file);
BufferedReader br = new BufferedReader(fileReader);
listOfStudents = readAndLoadFile(br);
System.out.println(listOfStudents.size());
fileReader.close();
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}
}
}
private static List<Student> readAndLoadFile(BufferedReader br) {
System.out.println("into method readAndLoadFile");
List<Student> listOfStudentsInfo = new ArrayList<Student>();
String st;
try {
while( (st = br.readLine()) != null) {
String[] pairs = st.split("\\|",-1);
if(pairs.length>1) {
System.out.println("data present");
Student student = new Student();
student.setFieldOne(pairs[0].trim());
student.setFieldTwo(pairs[1].trim());
student.setFieldThree( Integer.parseInt(pairs[2].trim()));
listOfStudentsInfo.add(student);
}
}
} catch (IOException e) {
e.printStackTrace();
}
return listOfStudentsInfo;
}
}
The .trim() is used to cut the unnecessary spaces from the content.
Happy coding and do subscribe!😉