【发布时间】:2013-09-19 12:02:51
【问题描述】:
我目前正在写我的论文,在这种情况下,我需要使用 java 开发一个元启发式算法。但是,我在尝试读取和存储数据时遇到了问题。
我的文件是一个文本文件,大约有 150 行。问题的一个例子是在第 5 行,其中声明了三个整数:30、38 和 1。我想将它们中的每一个存储为分别称为 L、T 和 S 的整数,这对于许多其他的线。
你们有谁知道怎么做的吗?如果需要,我可以将 txt 文件发送给您。
顺便说一句:这是我迄今为止尝试过的:
Main.java:
import java.io.IOException;
import java.io.FileWriter;
import java.io.BufferedWriter;
public class MAIN {
public static void main(String[] args) throws IOException {
Test.readDoc("TAP_T38L30C4F2S12_03.txt");
}
}
Test.java:
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class Test {
private static ArrayList<Integer> integerList = new ArrayList<Integer>();
public static Map<String, ArrayList<Integer>> data = new HashMap<String, ArrayList<Integer>>();
public static String aKey;
public static void readDoc(String File) {
try{
FileReader fr = new FileReader("TAP_T38L30C4F2S12_03.txt");
BufferedReader br = new BufferedReader(fr);
while(true) {
String line = br.readLine();
if (line == null)
break;
else if (line.matches("\\#\\s[a-zA-Z]")){
String key = line.split("\\t")[1];
line = br.readLine();
data.put(key, computeLine(line));
}
else if (line.matches("\\\\\\#\\s(\\|[a-zA-Z]\\|,?\\s?)+")){
String[] keys = line.split("\\t");
line = br.readLine();
ArrayList<Integer> results = computeLine(line);
for (int i=0; i<keys.length; i++){
aKey = aKey.replace("|", "");
// data.put(aKey, results.get(i));
data.put(aKey, results);
}
}
System.out.println(data);
}
} catch(Exception ex) {
ex.printStackTrace(); }
}
private static ArrayList<Integer> computeLine (String line){
String[] splitted = line.split("\\t");
for (String s : splitted) {
integerList.add(Integer.parseInt(s));
}
return integerList;
}
}
数据示例如下:
\# TAP instance
\# Note that the sequence of the data is important!
\#
\# |L|, |T|, |S|
30 38 1
\#
\# v
8213 9319 10187 12144 8206 ...
\#
\# w
7027 9652 9956 13973 6661 14751 ...
\#
\# b
1 1 1 1 1 ...
\#
\# c
1399 1563 1303 1303 2019 ...
\#
\# continues
【问题讨论】:
-
1. Java 不是 javascript。 2. 谷歌搜索“read file java”。 3. 再谷歌搜索“split line java”。 4. 你通过一点研究解决了你的问题。
-
If needed I can send you the txt file..没必要,只显示你到目前为止尝试过的内容。 -
大家好,感谢 cmets。老实说,我已经尝试了 4 个小时,但似乎找不到解决方案。 (反斜杠对不起标签)
-
代码更好!但是,如果您将问题改写为与您遇到的问题相匹配,您就会得到结果:我相信您在“拆分字符串”时遇到了问题...
-
嘿 ppeterka,谢谢。我想我不知道这个问题的正确标题是什么。我会尝试用你的建议多用谷歌搜索一下,看看我明白了。
标签: java bufferedreader filereader