java - 无法正确读取和显示文件内容

标签 java file readfile

我的程序包含几个选项,用于处理有关节目的用户输入数据(名称、日期、时间)。其中一个选项是读取文件并向用户显示其内容。虽然我的程序的这一部分正在工作,但它没有正确显示(如下所示)。我应该更改程序读取文件的方式吗?如果有任何关于我应该更改代码的建议,我将非常感激!谢谢。

这是我的代码:

//Method loadShows
public static void loadShows() throws IOException {
    //String to find file
    String findFile, file;
    //ask for location of file
    System.out.println("Enter Show File Location: ");
    //Read input
    findFile = in.readLine();

    file = findFile + "/show.txt";

    BufferedReader input = new BufferedReader(new FileReader(file));
    x = Integer.valueOf(input.readLine()).intValue();
    System.out.println("Loading " + x + " Shows");

    for(i = 0; i<=(x-1); i++) {
        name[i] = input.readLine();
        day[i] = input.readLine();
        time[i] = input.readLine(); 
    }

    for(i = 0; i<=(x-1); i++) {
        System.out.println("Name : " + name[i]);
        System.out.println("Day : " + day[i]);
        System.out.println("Time(2:30 am = 0230) : " + time[i] + "\r");
    }
}

这是输出:

Enter Show File Location: 
C:\Users\OneDrive\Desktop\MyFirstJavaProject
Loading 3 Shows
Name :  //***As you can see it isn't in order, or displayed correctly***    
Day : Suits
Time(2:30 am = 0230) : Monday

Name : 0130
Day : The Flash
Time(2:30 am = 0230) : Thursday

Name : 0845
Day : National Geographic
Time(2:30 am = 0230) : Sunday

这是我的文件内容:

3     
Suits
Monday
0130
The Flash
Thursday
0845
National Geographic
Sunday
0525

最佳答案

您只需一个即可:

public static void loadShows() throws IOException {
        BufferedReader br = new BufferedReader(new FileReader("C:\\Users\\adossantos\\file.txt"));
        try {
            StringBuilder sb = new StringBuilder();
            String line = br.readLine();

            while (line != null) {
                sb.append(line);
                sb.append(System.lineSeparator());
                line = br.readLine();
            }
            String everything = sb.toString();
            String[] values = everything.split("\n");

            for(int i = 0; i < values.length; i+=3) {

                if(i + 3 > values.length - 1  )
                    break;

                System.out.println("Name : " + values[i + 1]);
                System.out.println("Day : " + values[i + 2 ]);
                System.out.println("Time(2:30 am = 0230) : " + values[i + 3] + "\r");
            }
        } finally {
            br.close();
        }
    }

回应:

enter image description here

关于java - 无法正确读取和显示文件内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50645907/

相关文章:

java.util.NoSuchElementException 错误

java - 从 Cassandra 读取 timeuuid 值 - 使用 DataStax 连接器

java - JButton 没有出现在 JDialog 上

php - 如何在php中按文件大小对 ListView 进行排序

PHP readfile 与 file_get_contents

php - 在安全模式服务器中是否有替代 php readfile() 的方法?

java - OSGi DS : xml file is not generated

java - 素数计算器不会打印整数 '2' - 逻辑错误?

regex - 填充空间/制表符分隔,空列为0

file - 使用 postgres 复制命令导出数据时从 CHAR 列修剪数据