从文本文件中读取和查找字符串 [英] read and find string from text file
问题描述
我正在使用以下代码将文本文件内容加载到GUI:
I am loading text file contents to GUI using this code:
try {
BufferedReader br = new BufferedReader(new FileReader ("text.txt"));
String line;
while ((line = br.readLine()) != null) {
if (line.contains("TITLE")) {
jTextField2.setText(line.substring(11, 59));
}
}
in.close();
} catch (Exception e) {
}
然后是text.txt文件的内容:
Then contents of text.txt file:
JOURNAL journal name A12340001
TITLE Sound, mobility and landscapes of exhibition: radio-guided A12340002
tours at the Science Museum A12340003
AUTHOR authors name A12340004
在jTextField2
上,我得到以下一行:展览的声音,流动性和风景:无线电引导" .
问题是我不知道如何获取jTextField2
下一行科学馆旅游"的字符串..
On jTextField2
I am getting this line: "Sound, mobility and landscapes of exhibition: radio-guided".
The problem is I don't know how to get to jTextField2
the string of next line "tours at the Science Museum".
我想问一下如何在jTextField2
上同时显示这条线,即展览的声音,流动性和景观:科学馆的无线电导览" ?
I would like to ask how can I get both line on jTextField2
i.e. "Sound, mobility and landscapes of exhibition: radio-guided tours at the Science Museum"?
在此先感谢您的帮助.
推荐答案
如果您使用的是Java 8,并假设各列具有固定数量的字符,则可能会这样:
If you are using Java 8 and assuming that the columns have a fixed number of characters, you could something like this:
public static void main(String args[]) throws IOException {
Map<String, String> sections = new HashMap<>();
List<String> content = (List<String>)Files.lines(Paths.get("files/input.txt")).collect(Collectors.toList());
String lastKey = "";
for(String s : content){
String k = s.substring(0, 10).trim();
String v = s.substring(10, s.length()-9).trim();
if(k.equals(""))
k=lastKey;
sections.merge(k, v, String::concat);
lastKey=k;
}
System.out.println(sections.get("TITLE"));
}
第一列是键.如果键不存在,则使用最后一个键. Map
用于存储键和值.当键已经存在时,该值将通过串联与现有键合并.
The first column is the key. When the keys does not exist, the last key is used. A Map
is used to store the keys and the values. When the key already exist, the value is merged with the existing one by concatenation.
此代码输出预期的字符串:Sound, mobility and landscapes of exhibition: radio-guidedtours at the Science Museum
.
This code outputs the expected String: Sound, mobility and landscapes of exhibition: radio-guidedtours at the Science Museum
.
编辑:对于Java 7
For Java 7
public static void main(String args[]) {
Map<String, String> sections = new HashMap<>();
String s = "", lastKey="";
try (BufferedReader br = new BufferedReader(new FileReader("files/input.txt"))) {
while ((s = br.readLine()) != null) {
String k = s.substring(0, 10).trim();
String v = s.substring(10, s.length() - 9).trim();
if (k.equals(""))
k = lastKey;
if(sections.containsKey(k))
v = sections.get(k) + v;
sections.put(k,v);
lastKey = k;
}
} catch (IOException e) {
System.err.println("The file could not be found or read");
}
System.out.println(sections.get("TITLE"));
}
这篇关于从文本文件中读取和查找字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!