我有一个 .dat 格式的文件。这是一个示例
||= (N ) =|| 1|| 0.938 || --- || 0.5 || (****)|| 0.5 || 0 || 0 || 0 || 0.700 || (p)=2212, (n)=2112 ||
||= (\Delta ) =|| 2|| 1.232 || 0.118 || 1.5 || (****)|| 1.5 || 0 || 0 || 3 || 1.076 || (\Delta^{++})=2224, (\Delta^+)=2214, (\Delta^0)=2114, (\Delta^-)=1114 ||
||= (P_{11}(1440) ) =|| 3|| 1.462 || 0.391 || 0.5 || (****)|| 0.5 || 0 || 0 || 3 || 1.076 || 202212, 202112 ||
||= (S_{11}(1535) ) =|| 4|| 1.534 || 0.151 || 0.5 || ( ***)|| 0.5 || 0 || 0 || 3 || 1.076 || 102212, 102112 ||
我正在尝试使用 Scanner 读取此文件并用“||”分隔该行然后发送到 ArrayList 以供将来处理。这是我使用定界符的代码示例
String file = "data.dat";
Scanner s = null;
try {
s = new Scanner(new File(file)).useDelimiter("\\|\\|"); //here is the use of my delimiter
ArrayList<String> list = new ArrayList<String>();
while (s.hasNextLine()) { //notice I am using hasNextLine because each line must be unique to create the HashMap
list.add(s.nextLine());
}
s.close();
for (String string : list) { //Lets print out the values of the list
System.out.println(string);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
但我的输出仍然有分隔符的值,即输出如下:
||= (N ) =|| 1|| 0.938 || --- || 0.5 || (****)|| 0.5 || 0 || 0 || 0 || 0.700 || (p)=2212, (n)=2112 ||
||= (\Delta ) =|| 2|| 1.232 || 0.118 || 1.5 || (****)|| 1.5 || 0 || 0 || 3 || 1.076 || (\Delta^{++})=2224, (\Delta^+)=2214, (\Delta^0)=2114, (\Delta^-)=1114 ||
||= (P_{11}(1440) ) =|| 3|| 1.462 || 0.391 || 0.5 || (****)|| 0.5 || 0 || 0 || 3 || 1.076 || 202212, 202112 ||
||= (S_{11}(1535) ) =|| 4|| 1.534 || 0.151 || 0.5 || ( ***)|| 0.5 || 0 || 0 || 3 || 1.076 || 102212, 102112 ||
我已经搜索过,但没有找到有用的答案。我还看到一条关于“资源泄漏:''永远不会关闭”的警告,其中包含以下行
s = new Scanner(new File(file)).useDelimiter("\\|\\|");
如果线被打断,它就会消失
s = new Scanner(new File(file));
s.useDelimiter("\\|\\|");
感谢任何帮助。
最佳答案
您不需要使用反斜杠转义。而不是 \\|\\|
作为分隔符,只需在从文件中读取字符串后拆分它即可。
String file = "data.dat";
Scanner s = null;
try {
s = new Scanner(new File(file)); //no more delimiter. It's not needed
ArrayList<String> list = new ArrayList<String>();
while (s.hasNextLine()) {
String[] strings = s.nextLine().split("[||]");
for (int i = 0; i < strings.length; i++) {
list.add(strings[i]);
}
}
s.close();
for (String string : list) { //Lets print out the values of the list
System.out.println(string);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
这应该可以解决它。
关于nextLine 值的 Java 扫描器定界符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40259496/