9

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, 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 :

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

16 回答 16

14

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

返回可以从此输入流中读取(或跳过)的字节数的估计值,而不会被下一次调用此输入流的方法阻塞。

你可能想使用类似的东西

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

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

于 2010-05-19T09:09:33.860 回答
11

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

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

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

于 2010-05-19T09:09:19.773 回答
3

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

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

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

于 2010-05-19T09:09:47.533 回答
3
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();   
}
于 2010-05-19T09:14:50.540 回答
2

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

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

希望对你有帮助。。

于 2011-05-11T10:19:20.880 回答
1

您的代码跳过最后一行的原因是因为您放置fis.available() > 0而不是fis.available() >= 0

于 2014-11-24T01:25:52.937 回答
1

Java 8Files.lines中,您可以使用and轻松地将文本文件转换为带有流的字符串列表collect

private List<String> loadFile() {
    URI uri = null;
    try {
        uri = ClassLoader.getSystemResource("example.txt").toURI();
    } catch (URISyntaxException e) {
        LOGGER.error("Failed to load file.", e);
    }
    List<String> list = null;
    try (Stream<String> lines = Files.lines(Paths.get(uri))) {
        list = lines.collect(Collectors.toList());
    } catch (IOException e) {
        LOGGER.error("Failed to load file.", e);
    }
    return list;
}
于 2015-05-04T10:57:08.967 回答
1
//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);
        }




    }
}
于 2017-10-14T17:25:24.077 回答
0

试试这只是在谷歌搜索

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());
    }
  }
}
于 2010-05-19T09:10:11.150 回答
0

尝试像这样使用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();
于 2010-05-19T09:11:51.023 回答
0

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

谢谢。

于 2010-05-19T11:28:13.987 回答
0

用户扫描仪应该可以工作

         Scanner scanner = new Scanner(file);
         while (scanner.hasNextLine()) {
           System.out.println(scanner.nextLine());
         }
         scanner.close(); 
于 2013-07-30T15:22:47.427 回答
0
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);
    }
}
于 2013-10-29T04:59:38.470 回答
0
public class FilesStrings {

public static void main(String[] args) throws FileNotFoundException, IOException {
    FileInputStream fis = new FileInputStream("input.txt");
    InputStreamReader input = new InputStreamReader(fis);
    BufferedReader br = new BufferedReader(input);
    String data;
    String result = new String();

    while ((data = br.readLine()) != null) {
        result = result.concat(data + " ");
    }

    System.out.println(result);
于 2015-08-05T13:36:40.823 回答
0
    File file = new File("Path");

    FileReader reader = new FileReader(file);  

    while((ch=reader.read())!=-1)
    {
        System.out.print((char)ch);
    }

这对我有用

于 2018-10-02T09:22:13.063 回答
-3

用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);
            }
        }
    }
}
于 2014-02-09T12:37:23.203 回答