试图用Java读取txt文件

时间:2017-01-16 22:43:29

标签: java text

我应该为用户阅读并向屏幕显示一个简单的文本文件,我似乎无法弄明白。感谢任何帮助,谢谢。

import java.io.*;
import static java.lang.System.in;
import java.util.Scanner;

public class PersonReader 
{
    public static void main(String[] args) throws FileNotFoundException, IOException 
    {
        Scanner reader = new Scanner(System.in);
        String textFile = SafeInput.getString(reader, "What file would you like to read?: ");
        try(BufferedReader br = new BufferedReader(new FileReader(textFile + ".txt")))
        {
            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();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您没有打印最终的stringbuilder字符串。

import java.io.*;
import java.util.Scanner;

public class PersonReader {
    public static void main(String[] args) throws FileNotFoundException {
        Scanner reader = new Scanner(System.in);
        System.out.println("What file would you like to read?: ");
        String textFile = reader.nextLine();

        File f = new File(textFile + ".txt");
        if (f.isFile()) {
            Scanner sc = new Scanner(f);
            StringBuilder sb = new StringBuilder();
            while (sc.hasNextLine()) {
                sb.append(sc.nextLine() + System.lineSeparator());
            }
            System.out.println(sb);
            sc.close();
        }
        else {
            System.out.println("could not find file: " + textFile + ".txt");
        }
        reader.close();
    }
}