Read data from a text file using Java

后端 未结 16 1501
挽巷
挽巷 2020-12-10 05:35

I need to read a text file line by line using Java. I use available() method of FileInputStream to check and loop over the file. But while reading,

相关标签:
16条回答
  • 2020-12-10 05:52

    user scanner it should work

             Scanner scanner = new Scanner(file);
             while (scanner.hasNextLine()) {
               System.out.println(scanner.nextLine());
             }
             scanner.close(); 
    
    0 讨论(0)
  • 2020-12-10 05:53
        File file = new File("Path");
    
        FileReader reader = new FileReader(file);  
    
        while((ch=reader.read())!=-1)
        {
            System.out.print((char)ch);
        }
    

    This worked for me

    0 讨论(0)
  • 2020-12-10 05:58
    String file = "/path/to/your/file.txt";
    
    try {
    
        BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
        String line;
        // Uncomment the line below if you want to skip the fist line (e.g if headers)
        // line = br.readLine();
    
        while ((line = br.readLine()) != null) {
    
            // do something with line
    
        }
        br.close();
    
    } catch (IOException e) {
        System.out.println("ERROR: unable to read file " + file);
        e.printStackTrace();   
    }
    
    0 讨论(0)
  • 2020-12-10 05:58

    You can try FileUtils from org.apache.commons.io.FileUtils, try downloading jar from here

    and you can use the following method: FileUtils.readFileToString("yourFileName");

    Hope it helps you..

    0 讨论(0)
  • 2020-12-10 05:58

    The reason your code skipped the last line was because you put fis.available() > 0 instead of fis.available() >= 0

    0 讨论(0)
  • 2020-12-10 05:58

    Try this just a little search in Google

    import java.io.*;
    class FileRead 
    {
       public static void main(String args[])
      {
          try{
        // Open the file that is the first 
        // command line parameter
        FileInputStream fstream = new FileInputStream("textfile.txt");
        // Get the object of DataInputStream
        DataInputStream in = new DataInputStream(fstream);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String strLine;
        //Read File Line By Line
        while ((strLine = br.readLine()) != null)   {
          // Print the content on the console
          System.out.println (strLine);
        }
        //Close the input stream
        in.close();
        }catch (Exception e){//Catch exception if any
          System.err.println("Error: " + e.getMessage());
        }
      }
    }
    
    0 讨论(0)
提交回复
热议问题