非常奇怪的文件读取输出java

uinbv5nw  于 2021-07-08  发布在  Java
关注(0)|答案(1)|浏览(331)

所以,我从一个文本文件中读取单词并将它们保存在一个arraylists的arraylist中。它应该准确地打印文件中的单词。例如:

test1 test2 test3 test4 test5
test6 test7 test8
test9 test10

但它打印了这个:这里的实际输出为什么它会这样,以及如何修复它?以下是阅读代码:

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

任何帮助都将不胜感激。

neskvpey

neskvpey1#

while语句正在读取数据,但您没有对该数据执行任何操作。。
第一个 while(in.readLine() != null) { 将从文件中读取第一行
i、 e.试验1试验2试验3试验4试验5
但你什么都不做。
第二个 while ((in.read ()) != -1) { 将从文件中读取单个字符。所以 t 离开 est6 test7 test8 阅读人 word_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);
}

相关问题