【发布时间】:2011-07-17 15:40:22
【问题描述】:
如何在 Java 中将文件内容读入ArrayList<String>?
以下是文件内容:
cat
house
dog
.
.
.
只需将每个单词读入ArrayList。
【问题讨论】:
标签: java
如何在 Java 中将文件内容读入ArrayList<String>?
以下是文件内容:
cat
house
dog
.
.
.
只需将每个单词读入ArrayList。
【问题讨论】:
标签: java
这段 Java 代码读入每个单词并将其放入 ArrayList:
Scanner s = new Scanner(new File("filepath"));
ArrayList<String> list = new ArrayList<String>();
while (s.hasNext()){
list.add(s.next());
}
s.close();
如果您想逐行而不是逐字阅读,请使用s.hasNextLine() 和s.nextLine()。
【讨论】:
Scanner 比 BufferedReader 更短,并且没有例外需要处理。我想我已经习惯了在 Java 5 之前使用 BufferedReader 时 Scanner 不存在,尽管我已经使用 Java 5 和 6 很多年了。 Commons IO 库当然会提供最短的答案(如果其他人提到的),所以我现在通常使用它。
new Scanner(new File("filepath")).useDelimiter(System.lineSeparator()) 因为每个操作系统可能不同
你可以使用:
List<String> list = Files.readAllLines(new File("input.txt").toPath(), Charset.defaultCharset() );
来源:Java API 7.0
【讨论】:
Paths.get("input.txt")代替new File("input.txt").toPath(0
与commons-io 的单线:
List<String> lines = FileUtils.readLines(new File("/path/to/file.txt"), "utf-8");
同guava:
List<String> lines =
Files.readLines(new File("/path/to/file.txt"), Charset.forName("utf-8"));
【讨论】:
Charsets.UTF_8 而不是forName?
我发现的最简单的形式是......
List<String> lines = Files.readAllLines(Paths.get("/path/to/file.txt"));
【讨论】:
在 Java 8 中,您可以使用流和Files.lines:
List<String> list = null;
try (Stream<String> lines = Files.lines(myPathToTheFile))) {
list = lines.collect(Collectors.toList());
} catch (IOException e) {
LOGGER.error("Failed to load file.", e);
}
或者作为一个函数,包括从文件系统加载文件:
private List<String> loadFile() {
List<String> list = null;
URI uri = null;
try {
uri = ClassLoader.getSystemResource("example.txt").toURI();
} catch (URISyntaxException e) {
LOGGER.error("Failed to load file.", e);
}
try (Stream<String> lines = Files.lines(Paths.get(uri))) {
list = lines.collect(Collectors.toList());
} catch (IOException e) {
LOGGER.error("Failed to load file.", e);
}
return list;
}
【讨论】:
List<String> lines = Files.lines(Paths.get("./input.txt")).collect(Collectors.toList());
List<String> words = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new FileReader("words.txt"));
String line;
while ((line = reader.readLine()) != null) {
words.add(line);
}
reader.close();
【讨论】:
例如,您可以通过这种方式执行此操作(包含异常处理的完整代码):
BufferedReader in = null;
List<String> myList = new ArrayList<String>();
try {
in = new BufferedReader(new FileReader("myfile.txt"));
String str;
while ((str = in.readLine()) != null) {
myList.add(str);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null) {
in.close();
}
}
【讨论】:
//CS124 HW6 Wikipedia Relation Extraction
//Alan Joyce (ajoyce)
public List<String> addWives(String fileName) {
List<String> wives = new ArrayList<String>();
try {
BufferedReader input = new BufferedReader(new FileReader(fileName));
// for each line
for(String line = input.readLine(); line != null; line = input.readLine()) {
wives.add(line);
}
input.close();
} catch(IOException e) {
e.printStackTrace();
System.exit(1);
return null;
}
return wives;
}
【讨论】:
这是一个对我来说效果很好的解决方案:
List<String> lines = Arrays.asList(
new Scanner(new File(file)).useDelimiter("\\Z").next().split("\\r?\\n")
);
如果你不想要空行,你也可以这样做:
List<String> lines = Arrays.asList(
new Scanner(new File(file)).useDelimiter("\\Z").next().split("[\\r\\n]+")
);
【讨论】:
分享一些分析信息。通过一个简单的测试,读取大约 1180 行值需要多长时间。
如果您需要非常快速地读取数据,请使用旧的 BufferedReader FileReader 示例。我花了~8ms
扫描仪要慢得多。花了我大约 138 毫秒
漂亮的 Java 8 Files.lines(...) 是最慢的版本。花了我大约 388 毫秒。
【讨论】:
这是一个完整的程序示例:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class X {
public static void main(String[] args) {
File f = new File("D:/projects/eric/eclipseworkspace/testing2/usernames.txt");
try{
ArrayList<String> lines = get_arraylist_from_file(f);
for(int x = 0; x < lines.size(); x++){
System.out.println(lines.get(x));
}
}
catch(Exception e){
e.printStackTrace();
}
System.out.println("done");
}
public static ArrayList<String> get_arraylist_from_file(File f)
throws FileNotFoundException {
Scanner s;
ArrayList<String> list = new ArrayList<String>();
s = new Scanner(f);
while (s.hasNext()) {
list.add(s.next());
}
s.close();
return list;
}
}
【讨论】:
Scanner scr = new Scanner(new File(filePathInString));
/*Above line for scanning data from file*/
enter code here
ArrayList<DataType> list = new ArrayList<DateType>();
/*this is a object of arraylist which in data will store after scan*/
while (scr.hasNext()){
list.add(scr.next()); } /*上面的代码负责通过add函数在arraylist中添加数据*/
【讨论】:
添加此代码以对文本文件中的数据进行排序。
Collections.sort(list);
【讨论】: