从java中的文本文件读取输入
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20196211/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Read input from text file in java
提问by Ritesh Sangwan
I want to read input from a text file in java. I have a text file as follows.
我想从 java 中的文本文件读取输入。我有一个文本文件如下。
5
4
abcd
6
8
defgh
10
I want to read each character from file as a separate entity and work on that character individually like storing 4 in database separating abcd as a b c d and work on them individually.
我想从文件中读取每个字符作为一个单独的实体并单独处理该字符,例如将 4 存储在将 abcd 分隔为 abcd 的数据库中并单独处理它们。
What are the various ways to do it. What is the most efficient way.
有哪些不同的方法可以做到。什么是最有效的方法。
采纳答案by Maxim Shoustin
The easy way (and short) if you use Java 7:
如果您使用 Java 7 的简单方法(和简短):
List<String> lines = Files.readAllLines(Paths.get("path to file"), StandardCharsets.UTF_8);
It will put all file data to list where list item represents one row
它将所有文件数据放在列表中,其中列表项代表一行
回答by sanket
Use read line if your file has new lines.
如果您的文件有新行,请使用读取行。
String sCurrentLine;
br = new BufferedReader(new FileReader("C:\testing.txt"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
回答by rainkinz
If you want to use each character individually, then using a Scanner might be the way to go:
如果您想单独使用每个字符,那么使用 Scanner 可能是一种方法:
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class SOExample {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(new File("myfile.txt"));
sc.useDelimiter("");
while (sc.hasNext()) {
String s = sc.next();
if (s.trim().isEmpty()) {
continue;
}
System.out.println(s);
}
sc.close();
}
}
output:
输出:
5
4
a
b
c
d
6
8
d
e
f
g
h
1
0