List<Integer> numbers = new ArrayList<>();
for (String line : Files.readAllLines(Paths.get("/path/to/file.txt"))) {
for (String part : line.split("\\s+")) {
Integer i = Integer.valueOf(part);
numbers.add(i);
}
}
List<Integer> integers = new ArrayList<Integer>();
Scanner fileScanner = new Scanner(new File("c:\\file.txt"));
while (fileScanner.hasNextInt()){
integers.add(fileScanner.nextInt());
}
检查API . 处理不同类型的输入源,不同的分隔符和不同的数据类型还有更多选项 .
170
此示例代码显示了如何使用Java读取文件 .
import java.io.*;
/**
* This example code shows you how to read file in Java
*
* IN MY CASE RAILWAY IS MY TEXT FILE WHICH I WANT TO DISPLAY YOU CHANGE WITH YOUR OWN
*/
public class ReadFileExample
{
public static void main(String[] args)
{
System.out.println("Reading File from Java code");
//Name of the file
String fileName="RAILWAY.txt";
try{
//Create object of FileReader
FileReader inputFile = new FileReader(fileName);
//Instantiate the BufferedReader Class
BufferedReader bufferReader = new BufferedReader(inputFile);
//Variable to hold the one line data
String line;
// Read file line by line and print on the console
while ((line = bufferReader.readLine()) != null) {
System.out.println(line);
}
//Close the buffer reader
bufferReader.close();
}catch(Exception e){
System.out.println("Error while reading file line by line:" + e.getMessage());
}
}
}
4
看看这个例子,并尝试自己做:
import java.io.*;
public class ReadFile {
public static void main(String[] args){
String string = "";
String file = "textFile.txt";
// Reading
try{
InputStream ips = new FileInputStream(file);
InputStreamReader ipsr = new InputStreamReader(ips);
BufferedReader br = new BufferedReader(ipsr);
String line;
while ((line = br.readLine()) != null){
System.out.println(line);
string += line + "\n";
}
br.close();
}
catch (Exception e){
System.out.println(e.toString());
}
// Writing
try {
FileWriter fw = new FileWriter (file);
BufferedWriter bw = new BufferedWriter (fw);
PrintWriter fileOut = new PrintWriter (bw);
fileOut.println (string+"\n test of read and write !!");
fileOut.close();
System.out.println("the file " + file + " is created!");
}
catch (Exception e){
System.out.println(e.toString());
}
}
}
18
只是为了好玩,这里's what I' d可能在一个真实的项目中,我已经在使用我最喜欢的所有库(在本例中为Guava,以前称为Google Collections) .
String text = Files.toString(new File("textfile.txt"), Charsets.UTF_8);
List<Integer> list = Lists.newArrayList();
for (String s : text.split("\\s")) {
list.add(Integer.valueOf(s));
}
9 回答
使用Apache Commons(IO和Lang)进行简单/常见的事情 .
进口:
码:
完成 .
您可以使用Files#readAllLines()将文本文件的所有行都放入
List<String>
.教程:Basic I/O > File I/O > Reading, Writing and Creating text files
您可以使用String#split()根据正则表达式拆分
String
部分 .教程:Numbers and Strings > Strings > Manipulating Characters in a String
您可以使用Integer#valueOf()将
String
转换为Integer
.教程:Numbers and Strings > Strings > Converting between Numbers and Strings
您可以使用List#add()将元素添加到
List
.教程:Interfaces > The List Interface
因此,简而言之(假设文件没有空行也没有尾随/前导空格) .
如果您恰好是Java 8,那么您甚至可以使用Stream API,从Files#lines()开始 .
教程:Processing data with Java 8 streams
Java 1.5引入了Scanner类来处理来自文件和流的输入 .
它用于从文件中获取整数,看起来像这样:
检查API . 处理不同类型的输入源,不同的分隔符和不同的数据类型还有更多选项 .
此示例代码显示了如何使用Java读取文件 .
看看这个例子,并尝试自己做:
只是为了好玩,这里's what I' d可能在一个真实的项目中,我已经在使用我最喜欢的所有库(在本例中为Guava,以前称为Google Collections) .
好处:维护的代码不多(例如this) . 编辑:虽然值得注意的是,在这种情况下tschaible's Scanner solution没有更多的代码!
缺点:你显然可能不想为此添加新的库依赖项 . (再说一次,你在项目中不要使用Guava是愚蠢的 . ;-)
使用Java 7使用NIO.2读取文件
导入这些包:
这是读取文件的过程:
要一次读取文件的所有行:
到目前为止,所有答案都涉及逐行读取文件,将行作为
String
,然后处理String
.毫无疑问,这是最容易理解的方法,如果文件相当短(比如成千上万行),那么在效率方面也是可以接受的 . But if the file is long ,这是一种非常低效的方法,原因有两个:
每个角色都会被处理两次,一次是在构建
String
时,一次是在处理它时 .如果文件中有很多行,垃圾收集器将不是你的朋友 . 你正在为每一行构建一个新的
String
,然后当你移动到下一行时扔掉它 . 垃圾收集器最终将不得不处理所有这些String
对象,而这些对象在您之后必须清理 .如果您关心速度,那么阅读数据块然后逐字节而不是逐行处理它会好得多 . 每当你到达一个数字的末尾,你将它添加到你正在构建的
List
.会出现这样的事情:
上面的代码假设这是ASCII(虽然它可以很容易地调整为其他编码),并且任何非数字(特别是空格或换行符)代表数字之间的边界 . 它还假设文件以非数字结尾(实际上,最后一行以换行符结束),但同样,它可以调整以处理它没有的情况 .
这是基于_1585836的任何一种方法,也是作为这个问题的答案给出的 . 有一个非常类似的问题的详细调查in this question . 如果你想沿着多线程线走下去,你还有可能进一步改进它 .
读取文件,然后执行任何你想要的java8 Files.lines(Paths.get(“c://lines.txt”)) . collect(Collectors.toList());