[英]Java adding file contents to array list
Hi i am new to Java working with files. 嗨,我是Java的新手。 I have got a text file called banking.txt
located in C:
but when i try put its content into an ArrayList
and print it prints out nothing. 我有一个名为banking.txt
的文本文件位于C:
但是当我尝试将其内容放入ArrayList
并打印时,它什么都没打印出来。 Is the file path i am using incorrect or is it something different? 我使用的文件路径是否不正确或是否有所不同?
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);
}
}
Try to use InputStream 尝试使用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);
}
}
I would recommend using the lines method of Java 8: 我建议使用Java 8的lines方法:
Stream<String> content = Files.lines("C:\\banking.txt")
content.forEach(System.out::println);
I guess you need to use this code as the Scanner
: 我想你需要使用这个代码作为Scanner
:
Scanner in = new Scanner(new FileReader("C:\\banking.txt"));
This will read the file as a String and you can add it to Array. 这将以String形式读取文件,您可以将其添加到Array。 Check this post for more: Reading a plain text file in Java 查看这篇文章了解更多信息: 用Java读取纯文本文件
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.