繁体   English   中英

尝试读取Java中的txt文件

[英]Trying to read a txt file in Java

我应该在为用户阅读并在屏幕上显示一个简单的文本文件,但似乎无法弄清楚。 任何帮助表示赞赏,谢谢。

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();
        }
    }
}

您没有打印最终的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();
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM