aks*_*aks 81 java file-io arraylist text-files
我想读取包含空格分隔值的文本文件.值是整数.如何阅读并将其放入数组列表?
以下是文本文件内容的示例:
1 62 4 55 5 6 77
Run Code Online (Sandbox Code Playgroud)
我想把它放在一个arraylist中[1, 62, 4, 55, 5, 6, 77].我怎么能用Java做呢?
Bal*_*usC 170
您可以使用Files#readAllLines()将文本文件的所有行都放入List<String>.
for (String line : Files.readAllLines(Paths.get("/path/to/file.txt"))) {
// ...
}
Run Code Online (Sandbox Code Playgroud)
您可以使用基于正则表达式String#split()拆分String部分.
for (String part : line.split("\\s+")) {
// ...
}
Run Code Online (Sandbox Code Playgroud)
您可以使用Integer#valueOf()将a String转换为Integer.
Integer i = Integer.valueOf(part);
Run Code Online (Sandbox Code Playgroud)
您可以使用List#add()向元素添加元素List.
numbers.add(i);
Run Code Online (Sandbox Code Playgroud)
教程:接口>列表接口
因此,简而言之(假设文件没有空行也没有尾随/前导空格).
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);
}
}
Run Code Online (Sandbox Code Playgroud)
如果你恰好在Java 8上,那么你甚至可以使用Stream API来开始Files#lines().
List<Integer> numbers = Files.lines(Paths.get("/path/to/test.txt"))
.map(line -> line.split("\\s+")).flatMap(Arrays::stream)
.map(Integer::valueOf)
.collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)
tsc*_*ble 34
Java 1.5引入了Scanner类来处理来自文件和流的输入.
它用于从文件中获取整数,看起来像这样:
List<Integer> integers = new ArrayList<Integer>();
Scanner fileScanner = new Scanner(new File("c:\\file.txt"));
while (fileScanner.hasNextInt()){
integers.add(fileScanner.nextInt());
}
Run Code Online (Sandbox Code Playgroud)
检查API.处理不同类型的输入源,不同的分隔符和不同的数据类型还有更多选项.
Saj*_*han 18
此示例代码显示了如何使用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());
}
}
}
Run Code Online (Sandbox Code Playgroud)
Edd*_*nho 10
看看这个例子,并尝试自己做:
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());
}
}
}
Run Code Online (Sandbox Code Playgroud)
只是为了好玩,这是我在一个真正的项目中可能会做的事情,我已经在使用我最喜欢的所有库(在这种情况下是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));
}
Run Code Online (Sandbox Code Playgroud)
好处:维护自己的代码不多(与此相反).编辑:虽然值得注意的是,在这种情况下,tschaible的扫描仪解决方案没有更多的代码!
缺点:你显然可能不想为此添加新的库依赖项.(再说一次,你在项目中不要使用Guava是愚蠢的.;-)
| 归档时间: |
|
| 查看次数: |
501938 次 |
| 最近记录: |