[英]java.lang.NullPointerException when trying to read txt file in java
[英]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.