Java: How to read a text file

后端 未结 9 2263
青春惊慌失措
青春惊慌失措 2020-11-22 06:58

I want to read a text file containing space separated values. Values are integers. How can I read it and put it in an array list?

Here is an example of contents of t

9条回答
  •  梦如初夏
    2020-11-22 07:07

    This example code shows you how to read file in Java.

    import java.io.*;
    
    /**
     * This example code shows you how to read file in Java
     *
     * IN MY CASE RAILWAY IS MY TEXT FILE WHICH I WANT TO DISPLAY YOU CHANGE WITH YOUR   OWN      
     */
    
     public class ReadFileExample 
     {
        public static void main(String[] args) 
        {
           System.out.println("Reading File from Java code");
           //Name of the file
           String fileName="RAILWAY.txt";
           try{
    
              //Create object of FileReader
              FileReader inputFile = new FileReader(fileName);
    
              //Instantiate the BufferedReader Class
              BufferedReader bufferReader = new BufferedReader(inputFile);
    
              //Variable to hold the one line data
              String line;
    
              // Read file line by line and print on the console
              while ((line = bufferReader.readLine()) != null)   {
                System.out.println(line);
              }
              //Close the buffer reader
              bufferReader.close();
           }catch(Exception e){
              System.out.println("Error while reading file line by line:" + e.getMessage());                      
           }
    
         }
      }
    

提交回复
热议问题