0

I'm Lightcab and I am in the process of learning java. It is a fun experience and I'm totally loving it. So, today I planned to learn how to read data from a text file and it didn't go so well. I searched it on google and I got many examples. All of them were somewhat different from each other. I didn't even understand one of them. So, I'm here calling out you guys for help. What is the easiest method of reading multiple lines data from a text file? (Note: Please try to explain as much as possible). Have a nice day!

Lightcab
  • 23
  • 1
  • 7

1 Answers1

0

One way is:

String sCurrentLine; // variable, where we will save info from file

// open file

BufferedReader br = new BufferedReader(new FileReader("C:\\testing.txt"));

//while not end of file read line

while ((sCurrentLine = br.readLine()) != null) {
                System.out.println(sCurrentLine);}


//don't forget to close file

if (br != null) br.close();



--------------------
Example: 

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

    public class BufferedReaderExample {

        public static void main(String[] args) {

            try (BufferedReader br = new BufferedReader(new FileReader("C:\\testing.txt")))
            {

                String sCurrentLine;

                while ((sCurrentLine = br.readLine()) != null) {
                    System.out.println(sCurrentLine);
                }

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

        }
    }
Suresh Atta
  • 114,879
  • 36
  • 179
  • 284