【问题标题】:Read data from a text file using Java使用 Java 从文本文件中读取数据
【发布时间】:2010-05-19 09:05:03
【问题描述】:

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

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

【问题讨论】:

标签: java file-io fileinputstream


【解决方案1】:

您不应使用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。这也是我的首选方法。但是,in.close() 应该位于 finally 块中。
  • 我知道。然而,这需要另一个try...catch,因为close() 本身可能通过IOException。对于一个最小的例子来说变得有点难看。
  • 是的。当我决定刮掉 try/catch 时,我自己正在输入一个答案(不过你打败了我的答案)。
【解决方案2】:

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

【讨论】:

    【解决方案3】:

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

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

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

    【讨论】:

      【解决方案4】:
      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();   
      }
      

      【讨论】:

        【解决方案5】:

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

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

        希望对你有帮助..

        【讨论】:

          【解决方案6】:

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

          【讨论】:

            【解决方案7】:

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

            【讨论】:

              【解决方案8】:
              //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);
                      }
              
              
              
              
                  }
              }
              

              【讨论】:

                【解决方案9】:

                试试这只是在谷歌搜索一下

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

                【讨论】:

                • 请不要使用 DataInputStream 读取文本。不幸的是,像这样的例子被一次又一次地复制,所以你可以从你的例子中删除它。 vanillajava.blogspot.co.uk/2012/08/…
                【解决方案10】:

                尝试像这样使用 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();
                

                【讨论】:

                  【解决方案11】:

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

                  谢谢。

                  【讨论】:

                    【解决方案12】:

                    用户扫描仪应该可以工作

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

                    【讨论】:

                      【解决方案13】:
                      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);
                          }
                      }
                      

                      【讨论】:

                        【解决方案14】:
                        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);
                        

                        【讨论】:

                        • 您能详细说明一下吗?答案包含代码,请添加一些解释。谢谢。
                        【解决方案15】:
                            File file = new File("Path");
                        
                            FileReader reader = new FileReader(file);  
                        
                            while((ch=reader.read())!=-1)
                            {
                                System.out.print((char)ch);
                            }
                        

                        这对我有用

                        【讨论】:

                          【解决方案16】:

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

                          【讨论】:

                            猜你喜欢
                            • 1970-01-01
                            • 1970-01-01
                            • 1970-01-01
                            • 1970-01-01
                            • 1970-01-01
                            • 1970-01-01
                            • 1970-01-01
                            • 2015-11-24
                            • 1970-01-01
                            相关资源
                            最近更新 更多