【问题标题】:How to read records from a text file?如何从文本文件中读取记录?
【发布时间】:2014-11-15 04:16:45
【问题描述】:
I tried this:
public static void ReadRecord()
    {
        String line = null;
        try
        {
        FileReader fr = new FileReader("input.txt");
        BufferedReader br = new BufferedReader(fr);

        line = br.readLine();
         while(line != null)
         {
                System.out.println(line);
         }  

        br.close();
        fr.close();
        }
        catch (Exception e)
        {
        }
    }
}   

它不停地重复读取我之前输入并写入文件的一条记录...我如何读取记录并在读取记录时使用标记化?

【问题讨论】:

  • 您只是从文件中读取一行,然后执行while(line != null)line 永远不会在您的 while 循环范围内改变,因此它将永远循环。如果要继续读取文件,则需要循环读取文件。
  • 我正在为文件处理而苦苦挣扎。有人可以指导我进行标记化吗?

标签: java


【解决方案1】:

您必须使用br.readLine() 在循环中重复读取文件中的行。 br.readLine() 一次只读取一行。

做这样的事情:

while((line = br.readLine()) != null) {
    
     System.out.println(line);
}

如果您遇到问题,也请查看此链接。 http://www.mkyong.com/java/how-to-read-file-from-java-bufferedreader-example/

标记化

如果要将字符串拆分为标记,可以使用StringTokenizer 类或String.split() 方法。

StringTokenizer 类

StringTokenizer st = new StringTokenizer(line);
while (st.hasMoreTokens()) {
     System.out.println(st.nextToken());
}

st.hasMoreTokens() - 将检查是否存在更多令牌。
st.nextToken() - 将获得下一个令牌

String.split()

String[] result = line.split("\\s"); // split line into tokens
for (int x=0; x<result.length; x++) {
     System.out.println(result[x]);
}

line.split("\\s") - 将linespace 作为分隔符。它返回一个字符串数组。

【讨论】:

    【解决方案2】:

    试试这个

         while((line = br.readLine()) != null)
         {
                System.out.println(line);
         }  
    

    【讨论】:

      【解决方案3】:

      试试这个:

           BufferedReader br = new BufferedReader(new FileReader("input.txt"));
           while((line=br.readline())!=null)
           System.out.println(line);
      

      【讨论】:

        【解决方案4】:

        对于一个名为 access.txt 的文本文件,例如在您的 X 驱动器上定位,这应该可以工作。

        public static void readRecordFromTextFile throws FileNotFoundException
        
        {
            try {
                File file = new File("X:\\access.txt");
                Scanner sc = new Scanner(file);
                sc.useDelimiter(",|\r\n");
                System.out.println(sc.next());
                while (sc.hasNext()) {
                    System.out.println(sc.next());
                }
        
                sc.close();// closing the scanner stream
            } catch (FileNotFoundException e) {
        
                System.out.println("Enter existing file name");
        
                e.printStackTrace();
            }
        
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-01-10
          • 2015-08-01
          • 2012-10-01
          相关资源
          最近更新 更多