您好我是Java新手使用文件。我有一个名为banking.txt
的文本文件,位于C:
,但是当我尝试将其内容放入ArrayList
并打印时,它不会打印出来。我使用的文件路径是否不正确或是不同的东西?
import java.util.ArrayList;
import java.util.Scanner;
import java.io.*;
public class FileP {
public static void main(String[] args) throws FileNotFoundException {
Scanner read = new Scanner(new File("C:\\banking.txt"));
ArrayList<String> myList = new ArrayList<String>();
while(read.hasNextLine()) {
myList.add(read.nextLine());
}
System.out.println(myList);
}
}
答案 0 :(得分:2)
尝试使用InputStream
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.io.InputStream;
import java.io.InputStreamReader;
public class FileP {
public static void main(String[] args) throws IOException {
ArrayList<String> myList = new ArrayList<String>();
InputStream is = new FileInputStream("C:\\banking.txt");
BufferedReader buf = new BufferedReader(new InputStreamReader(is));
String line = buf.readLine();
StringBuilder sb = new StringBuilder();
while (line != null)
{
myList.add(line);
line = buf.readLine();
}
System.out.println("myList : " + myList);
}
}
答案 1 :(得分:1)
我建议使用Java 8的lines方法:
Stream<String> content = Files.lines("C:\\banking.txt")
content.forEach(System.out::println);
答案 2 :(得分:1)
我想您需要将此代码用作Scanner
:
Scanner in = new Scanner(new FileReader("C:\\banking.txt"));
这会将文件读取为String,您可以将其添加到Array。 查看此帖子了解更多信息: Reading a plain text file in Java