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

时间:2010-05-19 09:05:03

标签: java file-io fileinputstream

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

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

17 个答案:

答案 0 :(得分:14)

您不应该使用available()。它无法保证什么。来自API docs of 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

答案 1 :(得分:12)

使用Scanner怎么样?我认为使用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

答案 2 :(得分:3)

如果您想逐行阅读,请使用BufferedReader。它有一个readLine()方法,它将该行作为String返回,如果已到达文件的末尾,则返回null。所以你可以这样做:

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

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

答案 3 :(得分: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();   
}

答案 4 :(得分:2)

您可以尝试org.apache.commons.io.FileUtils中的FileUtils,try downloading jar from here

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

希望它可以帮助你..

答案 5 :(得分: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);
        }




    }
}

答案 6 :(得分:1)

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

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

答案 7 :(得分:1)

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

答案 8 :(得分:0)

    File file = new File("Path");

    FileReader reader = new FileReader(file);  

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

这对我有用

答案 9 :(得分: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);

答案 10 :(得分: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);
    }
}

答案 11 :(得分:0)

用户扫描程序应该可以使用

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

答案 12 :(得分:0)

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

感谢。

答案 13 :(得分: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();

答案 14 :(得分:0)

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

答案 15 :(得分:-2)

BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
// process the line.
}
br.close(); // close bufferreader after use

答案 16 :(得分:-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);
            }
        }
    }
}