使用 Java 从文本文件中读取数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2864117/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 13:50:35  来源:igfitidea点击:

Read data from a text file using Java

javafile-iofileinputstream

提问by Saran

I need to read a text file line by line using Java. I use available()method of FileInputStreamto check and loop over the file. But while reading, the loop terminates after the line before the last one. i.e., if the file has 10 lines, the loop reads only the first 9 lines. Snippet used :

我需要使用 Java 逐行读取文本文件。我使用available()方法FileInputStream来检查和循环文件。但是在阅读时,循环在最后一行之前的行之后终止。,如果文件有 10 行,则循环只读取前 9 行。使用的片段:

while(fis.available() > 0)
{
    char c = (char)fis.read();
    .....
    .....
}

回答by vodkhang

How about using Scanner? I think using Scanner is easier

使用扫描仪怎么样?我认为使用 Scanner 更容易

     private static void readFile(String fileName) {
       try {
         File file = new File(fileName);
         Scanner scanner = new Scanner(file);
         while (scanner.hasNextLine()) {
           System.out.println(scanner.nextLine());
         }
         scanner.close();
       } catch (FileNotFoundException e) {
         e.printStackTrace();
       }
     }

Read more about Java IO here

在此处阅读有关 Java IO 的更多信息

回答by aioobe

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

你不应该使用available(). 它不提供任何保证。来自以下API 文档available()

Returns an estimateof 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)

(取自http://www.exampledepot.com/egs/java.io/ReadLinesFromFile.html

回答by Chris

If you want to read line-by-line, use a BufferedReader. It has a readLine()method which returns the line as a String, or null if the end of the file has been reached. So you can do something like:

如果要逐行阅读,请使用BufferedReader. 它有一个readLine()方法将行作为字符串返回,如果已到达文件末尾,则返回 null。因此,您可以执行以下操作:

BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
String line;
while ((line = reader.readLine()) != null) {
 // Do something with line
}

(Note that this code doesn't handle exceptions or close the stream, etc)

(请注意,此代码不处理异常或关闭流等)

回答by Incognito

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());
    }
  }
}

回答by Ravindra Gullapalli

Try using java.io.BufferedReaderlike this.

尝试像这样使用java.io.BufferedReader

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();

回答by Richard H

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();   
}

回答by Parth

Yes, buffering should be used for better performance. Use BufferedReader OR byte[] to store your temp data.

是的,应该使用缓冲以获得更好的性能。使用 BufferedReader 或 byte[] 来存储您的临时数据。

thanks.

谢谢。

回答by Kallathiyan

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

您可以从 org.apache.commons.io.FileUtils 尝试 FileUtils,尝试从这里下载 jar

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

您可以使用以下方法: FileUtils.readFileToString("yourFileName");

Hope it helps you..

希望能帮到你。。

回答by Gautam

user scanner it should work

用户扫描仪它应该可以工作

         Scanner scanner = new Scanner(file);
         while (scanner.hasNextLine()) {
           System.out.println(scanner.nextLine());
         }
         scanner.close(); 

回答by Jayanta Rout

public class ReadFileUsingFileInputStream {

/**
* @param args
*/
static int ch;

public static void main(String[] args) {
    File file = new File("C://text.txt");
    StringBuffer stringBuffer = new StringBuffer("");
    try {
        FileInputStream fileInputStream = new FileInputStream(file);
        try {
            while((ch = fileInputStream.read())!= -1){
                stringBuffer.append((char)ch);  
            }
        }
        catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println("File contents :");
    System.out.println(stringBuffer);
    }
}