Read data from a text file using Java

后端 未结 16 1502
挽巷
挽巷 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 06:11

    Simple code for reading file in JAVA:

    import java.io.*;
    
    class ReadData
    {
        public static void main(String args[])
        {
            FileReader fr = new FileReader(new File("<put your file path here>"));
            while(true)
            {
                int n=fr.read();
                if(n>-1)
                {
                    char ch=(char)fr.read();
                    System.out.print(ch);
                }
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-10 06:13
    //The way that I read integer numbers from a file is...
    
    import java.util.*;
    import java.io.*;
    
    public class Practice
    {
        public static void main(String [] args) throws IOException
        {
            Scanner input = new Scanner(new File("cards.txt"));
    
            int times = input.nextInt();
    
            for(int i = 0; i < times; i++)
            {
                int numbersFromFile = input.nextInt();
                System.out.println(numbersFromFile);
            }
    
    
    
    
        }
    }
    
    0 讨论(0)
  • 2020-12-10 06:19

    You should not use available(). It gives no guarantees what so ever. From the API docs of available():

    Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream.

    You would probably want to use something like

    try {
        BufferedReader in = new BufferedReader(new FileReader("infilename"));
        String str;
        while ((str = in.readLine()) != null)
            process(str);
        in.close();
    } catch (IOException e) {
    }
    

    (taken from http://www.exampledepot.com/egs/java.io/ReadLinesFromFile.html)

    0 讨论(0)
  • 2020-12-10 06:19

    Try using java.io.BufferedReader like this.

    java.io.BufferedReader br = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(fileName)));
    String line = null;
    while ((line = br.readLine()) != null){
    //Process the line
    }
    br.close();
    
    0 讨论(0)
提交回复
热议问题