java—编译的程序没有输出

i2byvkas  于 2021-07-07  发布在  Java
关注(0)|答案(1)|浏览(346)

我不明白为什么我的输出为零。。。代码在我看来是正确的,编译起来没有问题(除了缺少输出)。我试过绝对路径。文本文件与类存储在同一文件夹中。我是不是漏掉了什么明显的东西?

public class File {

    public static void main(String[] args) throws FileNotFoundException {
        String filename = "./inputD2.txt";
        readFile(filename);
        System.out.println( readFile(filename));
    }
    private static List<String> readFile(String filename) {
        List<String> records = new ArrayList<>();
        try {
            BufferedReader reader = new BufferedReader(new FileReader(filename));
            String line;
            while ((line = reader.readLine()) != null) {
                records.add(line);
            }
            reader.close();
            return records;
        }
        catch (Exception e) {
            System.err.format("Exception occurred trying to read '%s'.", filename);
            e.printStackTrace();
            return null;
        }
    }
}
jogvjijk

jogvjijk1#

package com.test;

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;

public class FileReaderTest {

    public static void main(String[] args) {
        String filename = "F:\\Sixth_workspace\\Sampleproject\\src\\main\\resources\\try.txt";
        System.out.println("Reading from the text file" + " " + readFile(filename));

    }

    private static List<String> readFile(String filename) {

        List<String> records;
        try {
            records = new ArrayList<String>();
            BufferedReader reader = new BufferedReader(new FileReader(filename));
            String line;
            while ((line = reader.readLine()) != null) {
                records.add(line);
            }
            reader.close();
            return records;
        } catch (Exception e) {

            System.err.println("Exception occurred trying to read '%s'." + filename);
            e.printStackTrace();
            return null;
        }
    }
}

我修改了你的代码,得到了想要的结果。在此处使用文本文件的完整路径

F:\\Sixth_workspace\\Sampleproject\\src\\main\\resources\\try.txt

是我的全部道路。
变化:
更改了类名
给定文本文件的完整路径
使用Java1.8(要求1.5以上)

相关问题