1

Below I have the following code to read in a file and go through it line by line.. This is using java's BufferedReader class. That I am fine with.

String filename = "C:\\test.txt"
String line = null;

FileReader fileReader = new FileReader(filename);
BufferedReader bufferedReader = new BufferedReader(fileReader);

try {
    while (((line = bufferedReader.readLine()) != null)) {

    //do the following....

   }

} catch (IOException) {
    e.printStackTrace();
    }

However I want to now start using InputStreamReader in Spring / Java. I have the below code written but I am unsure how I can step through my file line by line. Really confused over this part. Anyone have any ideas or know how this can be done?

String filepath= "C:\\test.txt" 
File filename= new File(filepath);

try {
    InputStream fileInputStream = new BOMInputStream(new fileInputStream(filename));

// now want to step through the file, line by line..

} catch (IOException) {
    e.printStackTrace();
    }

Thanks

TCP
  • 33
  • 2
  • 8

3 Answers3

0

This is how you can read your input file byte by byte using InputStreamReader.

    char[] chars = new char[100];
    try {
        InputStream inputStream       = new FileInputStream("C:\\test.txt");
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"UTF-8");           
        inputStreamReader.read(chars);          
        System.out.println(new String(chars).trim());
    } catch (IOException e) {
        e.printStackTrace();
    }
K. Singh
  • 1
  • 1
0

Check this out -

String filename = "C:\\test.txt"
String line = null;

FileInputStream fileInputStream = new FileInputStream(filename);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fileInputStream));

try {
    while (((line = bufferedReader.readLine()) != null)) {

    //do the following....

   }

} catch (IOException) {
    e.printStackTrace();
}
Bhushan Bhangale
  • 10,921
  • 5
  • 43
  • 71
0
public static void main(String[] args) {
    try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("c:\\test.txt")))) {

        reader.lines().forEach(line -> {
            // do what you want with the line
        });

    } catch (IOException e) {
        throw new RuntimeException(e);
    }

}
andrucz
  • 1,971
  • 2
  • 18
  • 30