【问题标题】:Reading a text file in java在java中读取文本文件
【发布时间】:2010-01-12 13:56:28
【问题描述】:

当每行都包含整数、字符串和双精度时,我如何在 Java 中读取 .txt 文件并将每一行放入数组中?而且每一行都有不同数量的单词/数字。

如果这个问题有点愚蠢,我是一个完整的 Java 菜鸟,很抱歉。

谢谢

【问题讨论】:

  • 请在你的问题中更具体一些,你想对每一行做什么?
  • 这个问题应该对你有帮助:stackoverflow.com/questions/224952
  • @Fabian Steeg:您链接到的问题并未解决像这样处理不同数据类型的问题。
  • @Bemrose,我不完全确定问题作者的意思,但我将其理解为每一行都可以包含不同种类和数量的数字。但是,是的,我不知道。

标签: java file-io


【解决方案1】:

试试Scanner 类,它没人知道,但几乎可以对文本做任何事情。

要获得文件的阅读器,请使用

File file = new File ("...path...");
String encoding = "...."; // Encoding of your file
Reader reader = new BufferedReader (new InputStreamReader (
    new FileInputStream (file), encoding));

... use reader ...

reader.close ();

你应该真正指定编码,否则当你遇到变音符号、Unicode等时你会得到奇怪的结果。

【讨论】:

  • +1 用于指出扫描仪。我以前没听说过。有趣的课程。
  • “没有人知道扫描仪”。至少对我来说是正确的。扫描仪也可以用作: Scanner sc = new Scanner(new File("fileName")); //知道为什么不这样使用它?
  • @sttaq:因为它使用默认编码。读取数据时切勿使用默认编码。始终找出输入是什么或指定您的代码接受什么编码;无论哪种方式,都要把它钉在特定的东西上。
【解决方案2】:

最简单的选择是简单地使用Apache Commons IO JAR 并导入 org.apache.commons.io.FileUtils 类。使用这个类有很多可能性,但最明显的应该是:

List<String> lines = FileUtils.readLines(new File("untitled.txt"));

就这么简单。

“不要重新发明轮子。”

【讨论】:

    【解决方案3】:

    Java 中读取文件的最佳方法是打开,逐行读取并处理它并关闭流

    // Open the file
    FileInputStream fstream = new FileInputStream("textfile.txt");
    BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
    
    String strLine;
    
    //Read File Line By Line
    while ((strLine = br.readLine()) != null)   {
      // Print the content on the console - do what you want to do
      System.out.println (strLine);
    }
    
    //Close the input stream
    fstream.close();
    

    要了解有关如何在 Java 中读取文件的更多信息,check out the article

    【讨论】:

      【解决方案4】:

      你的问题不是很清楚,所以我只回答“阅读”部分:

      List<String> lines = new ArrayList<String>();
      BufferedReader br = new BufferedReader(new FileReader("fileName"));
      String line = br.readLine();
      while (line != null)
      {
          lines.add(line);
          line = br.readLine();
      }
      

      【讨论】:

        【解决方案5】:

        常用:

            String line = null;
            File file = new File( "readme.txt" );
        
            FileReader fr = null;
            try
            {
                fr = new FileReader( file );
            } 
            catch (FileNotFoundException e) 
            {  
                System.out.println( "File doesn't exists" );
                e.printStackTrace();
            }
            BufferedReader br = new BufferedReader( fr );
        
            try
            {
                while( (line = br.readLine()) != null )
            {
                System.out.println( line );
            }
        

        【讨论】:

        • 欢迎来到 Stack Overflow!谢谢你的帖子!请不要在您的帖子中使用签名/标语。您的用户框算作您的签名,您可以使用您的个人资料发布您喜欢的任何关于您自己的信息。 FAQ on signatures/taglines 特别是,请不要包含您的网站 URL,因为您的帖子可能会被标记为垃圾邮件。
        • @Kamil 在将 java import.io.* 添加到顶部并包含该类之后,这对我来说很好,除了 cmd 窗口的输出在每个字母之间有一个空格。如何避免输出中的空格。
        【解决方案6】:

        @user248921 首先,您可以在字符串数组中存储任何内容,因此您可以创建字符串数组并将一行存储在数组中,并在需要时在代码中使用值。您可以使用以下代码将异构(包含字符串、整数、布尔值等)行存储在数组中。

        public class user {
         public static void main(String x[]) throws IOException{
          BufferedReader b=new BufferedReader(new FileReader("<path to file>"));
          String[] user=new String[500];
          String line="";
          while ((line = b.readLine()) != null) {
           user[i]=line; 
           System.out.println(user[1]);
           i++;  
           }
        
         }
        }
        

        【讨论】:

          【解决方案7】:

          这是使用流和收集器的好方法。

          List<String> myList;
          try(BufferedReader reader = new BufferedReader(new FileReader("yourpath"))){
              myList = reader.lines() // This will return a Stream<String>
                           .collect(Collectors.toList());
          }catch(Exception e){
              e.printStackTrace();
          }
          

          使用 Streams 时,您还可以使用多种方法来过滤、操作或减少输入。

          【讨论】:

            【解决方案8】:

            对于 Java 11,您可以使用下一个简短的方法:

              Path path = Path.of("file.txt");
              try (var reader = Files.newBufferedReader(path)) {
                  String line;
                  while ((line = reader.readLine()) != null) {
                      System.out.println(line);
                  }
              }
            

            或者:

            var path = Path.of("file.txt");
            List<String> lines = Files.readAllLines(path);
            lines.forEach(System.out::println);
            

            或者:

            Files.lines(Path.of("file.txt")).forEach(System.out::println);
            

            【讨论】:

              猜你喜欢
              • 2016-02-29
              • 1970-01-01
              • 1970-01-01
              • 2016-08-08
              • 1970-01-01
              • 1970-01-01
              • 2011-01-12
              • 1970-01-01
              相关资源
              最近更新 更多