【问题标题】:Very strange File reading output Java很奇怪的文件读取输出Java
【发布时间】:2021-02-27 22:15:47
【问题描述】:

所以,我从文本文件中读取单词并将它们保存在 ArrayList 的 ArrayList 中。它应该完全按照文件中的内容打印单词。例如:

test1 test2 test3 test4 test5
test6 test7 test8
test9 test10

但它会打印:Actual output here 为什么它会有这样的行为以及如何解决它? 下面是阅读代码:

package com.company;

import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.InputMismatchException;
import java.util.Scanner;

public class WordOrder {
    public ArrayList<ArrayList<String>> LinesList;
    public ArrayList<String> Words_per_line_list;
    protected String FileName;
    protected File file;
    public WordOrder(){
        LinesList = new ArrayList<>();
        Words_per_line_list = new ArrayList<>();
    }
public void wordReading() throws IOException, IndexOutOfBoundsException{
        String word_to_be_read;
            Scanner scan = new Scanner (System.in);
            System.out.println ("Enter the name of the file");
            FileName = scan.nextLine ();
            file = new File(FileName);
            BufferedReader in = new BufferedReader(new FileReader (FileName));
            if(in.read () == -1){
                throw new IOException ("File does not exist or cannot be accessed");
            }
            System.out.println ("Test");
            int i =0, j = 0;
            while(in.readLine() != null) {
                LinesList.add(i, Words_per_line_list);
                while ((in.read ()) != -1) {
                    word_to_be_read = in.readLine ();
                    Words_per_line_list.add(j, word_to_be_read);
                    System.out.println (LinesList.get (i).get (j));
                    j++;
                }
                i++;
            }
    }

任何帮助将不胜感激。

【问题讨论】:

  • 什么是 LinesList 和 Words_per_line_list?你没有展示他们的定义/创作。
  • @pcoates 这是两个 ArrayList。 LinesList 是列表列表,而 Words_per_line_list 是字符串列表。它类似于:```LinesList>```

标签: java file arraylist io


【解决方案1】:

while 语句正在读取数据,但您没有对该数据执行任何操作..

第一个while(in.readLine() != null) { 将读取文件的第一行

即测试1 测试2 测试3 测试4 测试5

但你什么也没做。

第二个while ((in.read ()) != -1) { 将从文件中读取一个字符。所以t离开est6 test7 test8word_to_be_read = in.readLine ();读取,然后是下一行的t,留下est9 test10给下一个readline

您可以在外部 while 中将该行读入变量中,然后在 while 循环内处理您需要的行。

String line;
while((line = in.readLine()) != null) {
    // process the line however you need to
    System.out.println(line);
}

【讨论】:

  • 谢谢,但我还有一个问题。我应该在while(in.readLine() != null)中设置什么条件,以便迭代直到EOF?
  • 检查 != null 将迭代直到 EOF。从 javadoc... readline() Reads a line of text. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), a carriage return followed immediately by a line feed, or by reaching the end-of-file (EOF).returns null if the end of the stream has been reached without reading any characters
猜你喜欢
  • 1970-01-01
  • 2023-01-29
  • 2015-03-26
  • 1970-01-01
  • 2012-12-02
  • 1970-01-01
  • 1970-01-01
  • 2017-04-06
  • 2016-10-02
相关资源
最近更新 更多