![](/img/trans.png)
[英]Java: How do I read 4 numbers from each line in a file. And put them into variables?
[英]Read different variables from a file [java] and put them into a JList
我在编写一个应该能够从.txt文件读取异构功能的代码时遇到一些困难。 这是一个示例文件:
size = 1.523763e-13 Type = aBc,KCd,EIf
我需要找到此功能,然后将其放在netbeans的Jlist中。
为了找到size变量,我曾想使用BufferedReader类,但是我不知道下一步该怎么做!
有什么帮助吗? 我的代码到目前为止:
public String findSize() {
String spec = "";
try {
BufferedReader reader = new BufferedReader(new FileReader("sample.txt"));
String line = reader.readLine();
while(line!=null) {
if (line.contains("size")) {
for(int i = line.indexOf("size")+1, i = line.length(), i++)
spec +=...;
您可以通过拆分通过BufferedReader
或Scanner
读取的字符串来轻松实现此目的。
在下面的示例中,我使用了Scanner
并正在读取System.in
的行。 您可以替换它以从源文件中读取行。
这是代码片段:
public static void main (String[] args)
{
Scanner in = new Scanner(System.in);
List<String> typeString;
while(in.hasNext()) {
String[] str = in.nextLine().split("=");
System.out.println("Size: " + str[1].split(" ")[0] + " Type: " + str[2]);
typeString = new ArrayList<>(Arrays.asList(str[2].split(", ")));
}
}
请注意,这仅用于演示目的。 您可以拆分字符串并播放子字符串,然后随时存储它们。
输入:
size=1.523763e-13 Type=aBc, KCd, EIf
输出:
Size: 1.523763e-13 Type: aBc, KCd, EIf
typeString --> {aBc, KCd, EIf}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.