Java 从文本文件中读取并查找字符串
我正在使用以下代码将文本文件内容加载到GUI:Java 从文本文件中读取并查找字符串,java,java-io,Java,Java Io,我正在使用以下代码将文本文件内容加载到GUI: try { BufferedReader br = new BufferedReader(new FileReader ("text.txt")); String line; while ((line = br.readLine()) != null) { if (line.contains("TITLE")) { jTextField2.setText
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文件的内容:
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
我想问一下,我如何才能在jTextField2
上获得这两条线路,即“展览的声音、流动性和景观:科学博物馆的无线电导游”
提前感谢您的帮助。如果您使用的是Java 8,并且假设列具有固定数量的字符,您可以这样做:
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"));
}
如果您使用的是Java 8,并且假设列具有固定数量的字符,则可以如下所示:
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"));
}
第一列为空(所有空格)表示一行是前一行的延续。因此,您可以缓冲这些行并重复连接它们,直到得到非空的第一列,然后写入/打印整行
try {
BufferedReader br = new BufferedReader(new FileReader("text.txt")) ;
String line ;
String fullTitle = "" ;
while ((line = br.readLine()) != null) {
//extract the fields from the line
String heading = line.substring(0, 9) ;
String titleLine = line.substring(10, 69) ;
//does not select on "TITLE", prints all alines
if(heading.equals(" ")) {
fullTitle = fullTitle + titleLine ;
} else {
System.out.println(fullTitle) ;
fullTitle = titleLine ;
}
}
System.out.println(fullTitle) ; //flush the last buffered line
} catch (Exception e) {
System.out.println(e) ;
}
第一列为空(所有空格)表示一行是前一行的延续。因此,您可以缓冲这些行并重复连接它们,直到得到非空的第一列,然后写入/打印整行
try {
BufferedReader br = new BufferedReader(new FileReader("text.txt")) ;
String line ;
String fullTitle = "" ;
while ((line = br.readLine()) != null) {
//extract the fields from the line
String heading = line.substring(0, 9) ;
String titleLine = line.substring(10, 69) ;
//does not select on "TITLE", prints all alines
if(heading.equals(" ")) {
fullTitle = fullTitle + titleLine ;
} else {
System.out.println(fullTitle) ;
fullTitle = titleLine ;
}
}
System.out.println(fullTitle) ; //flush the last buffered line
} catch (Exception e) {
System.out.println(e) ;
}
你可以这样做
首先,将整个文件读入字符串对象。
然后得到标题和作者的索引
比如intstart=str.indexOf(“TITLE”);int end=str.indexOf(“作者”)代码>
然后将标题的长度添加到开始索引start+=“TITLE.length()代码>
并从结束索引end-=“AUTHOR”.length()中减去作者的长度代码>
最后你有了你想要的文本的开始和结束索引。
所以,让文本像这样
String title=str.subString(start,end);
你可以这样做
首先,将整个文件读入字符串对象。
然后得到标题和作者的索引
比如intstart=str.indexOf(“TITLE”);int end=str.indexOf(“作者”)代码>
然后将标题的长度添加到开始索引start+=“TITLE.length()代码>
并从结束索引end-=“AUTHOR”.length()中减去作者的长度代码>
最后你有了你想要的文本的开始和结束索引。
所以,让文本像这样
String title=str.subString(start,end);
为什么不创建一个MyFile
类来为您进行解析,将键值对存储在Map
中,然后您就可以访问它了。这将使您的代码更具可读性,并且更易于维护
如下所示:
public class MyFile {
private Map<String, String> map;
private String fileName;
public MyFile(String fileName) {
this.map = new HashMap<>();
this.fileName = fileName;
}
public void parse() throws IOException {
BufferedReader br = new BufferedReader(new FileReader(fileName));
String line = br.readLine();
String key = "";
while (line != null) {
//Only update key if the line starts with non-whitespace
key = line.startsWith(" ") ? title : line.substring(0, line.indexOf(" ")).trim();
//If the key is contained in the map, append to the value, otherwise insert a new value
map.put(key, map.get(key) == null ? line.substring(line.indexOf(" "), 59).trim() : map.get(key) + line.substring(line.indexOf(" "), 59).trim());
line = br.readLine();
}
}
public String getEntry(String key) {
return map.get(key);
}
public String toString() {
StringBuilder sb = new StringBuilder();
for (Entry entry:map.entrySet()) {
sb.append(entry.getKey()).append(" : ").append(entry.getValue()).append("\n");
}
return sb.toString();
}
}
这允许使用可变长度的键
允许您单独处理异常,然后轻松引用文件内容,如下所示:
MyFile journalFile = new MyFile("text.txt");
try {
journalFile.parse();
} catch (IOException e) {
System.err.println("Malformed file");
e.printStackTrace();
}
jTextField2.setText(journalFile.getEntry("TITLE"));
为什么不创建一个MyFile
类来为您进行解析,将键值对存储在Map
中,然后您就可以访问它了。这将使您的代码更具可读性,并且更易于维护
如下所示:
public class MyFile {
private Map<String, String> map;
private String fileName;
public MyFile(String fileName) {
this.map = new HashMap<>();
this.fileName = fileName;
}
public void parse() throws IOException {
BufferedReader br = new BufferedReader(new FileReader(fileName));
String line = br.readLine();
String key = "";
while (line != null) {
//Only update key if the line starts with non-whitespace
key = line.startsWith(" ") ? title : line.substring(0, line.indexOf(" ")).trim();
//If the key is contained in the map, append to the value, otherwise insert a new value
map.put(key, map.get(key) == null ? line.substring(line.indexOf(" "), 59).trim() : map.get(key) + line.substring(line.indexOf(" "), 59).trim());
line = br.readLine();
}
}
public String getEntry(String key) {
return map.get(key);
}
public String toString() {
StringBuilder sb = new StringBuilder();
for (Entry entry:map.entrySet()) {
sb.append(entry.getKey()).append(" : ").append(entry.getValue()).append("\n");
}
return sb.toString();
}
}
这允许使用可变长度的键
允许您单独处理异常,然后轻松引用文件内容,如下所示:
MyFile journalFile = new MyFile("text.txt");
try {
journalFile.parse();
} catch (IOException e) {
System.err.println("Malformed file");
e.printStackTrace();
}
jTextField2.setText(journalFile.getEntry("TITLE"));
这实际上与Swing或I/O无关,而是解析数据。。从硬编码的字符串开始(在代码中),将其解析为表示命令行应用程序中每个条目(而不是行)的对象。文件中有固定数量的行吗?@Ni。不幸的是,文件选项卡是否分开?这一行是否总是在标题行之后?这实际上与Swing或I/O无关,而是解析数据。。从硬编码的字符串开始(在代码中),将其解析为表示命令行应用程序中每个条目(而不是行)的对象。文件中有固定数量的行吗?@Ni。不幸的是,您的文件选项卡是否分开了?这一行是否总是在标题行之后?不幸的是,我应该使用Java 7,@joel314 Java 7也有相同的方式吗?给您。同样的想法,代码并不像Java8中那样干净。我希望有帮助。谢谢你,我已经检查过了,我也接受你的回答+1我很抱歉我经常改变选择哪一个答案是可以接受的还是合适的,决定这一点对我来说花了一点时间,我尝试扩展代码以达到我的目的,@joel314的代码比iAN2TEDV的代码灵活。不幸的是,我应该使用Java 7,@joel314对Java 7也有同样的方法吗?给你。同样的想法,代码并不像Java8中那样干净。我希望有帮助。谢谢你,我已经检查过了,我也接受你的回答+1我很抱歉我经常改变选择哪一个答案是可以接受的或合适的,决定这一点对我来说花了一点时间,我试着为我的目的扩展代码,@joel314的代码比iAN2TEDV的代码灵活。如果作者
也有3或5行作者姓名,它可以工作吗?因为在文本文件中,子字符串(0,9)中可以有几个空格。如果作者
也有3行或5行作者姓名,它就可以工作了?因为文本文件中的子字符串(0,9)中可以有几个空格。谢谢你的回答,你的代码工作得很好+1我想问一下,如果是TITLE子字符串(11,59)
和AUTHOR case子字符串(11,18)
,我是否可以编写类似TITLE->journalFile.parse()的内容代码>和作者->journalFile.parse2()代码>?@hub为什么要这样做?你只想在某些情况下的部分条目?我有大约20个关键字,如标题,作者,隶属关系,。。。每个关键字都应该使用不同的子字符串
,我想我可以用不同的子字符串
,为其他关键字实现你的代码,但我不能。我更新了一点答案。它现在允许可变长度的键和值。注意:键和值对应限制为59个字符,并用“
分隔。如果某个值是上一个键的一部分,则该行也应以“”开头。
谢谢您的回答,您的代码工作正常+我想问一下