从文本文件中读取和查找字符串
read and find string from text file
我正在使用以下代码将文本文件内容加载到 GUI:
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
我收到这条线:"Sound, mobility and landscapes of exhibition: radio-guided"。
问题是我不知道如何到达 jTextField2
下一行的字符串 "tours at the Science Museum".
我想问一下如何在 jTextField2
上获得两条线,即 "Sound, mobility and landscapes of exhibition: radio-guided tours at the Science Museum"?
提前感谢您的帮助。
如果您使用 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"));
}
第一列是键。当密钥不存在时,使用最后一个密钥。 Map
用于存储键和值。当键已经存在时,该值通过连接与现有的值合并。
此代码输出预期的字符串:Sound, mobility and landscapes of exhibition: radio-guidedtours at the Science Museum
。
编辑: 对于 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"));
}
第一列为空(所有空格)表示该行是前一行的延续。所以你可以缓冲这些行并重复连接它们,直到你得到一个非空的第一列,然后 write/print 整行。
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) ;
}
你可以做到
首先将整个文件读入一个字符串对象。
然后获取 TITLE 和 AUTHOR 的索引
喜欢 int start=str.indexOf("TITLE"); and int end=str.indexOf("AUTHOR");
然后将 TITLE 的长度添加到起始索引 start+="TITLE".length();
并从结束索引中减去 AUTHOR 的长度 end-="AUTHOR".length();
最后你有了你想要的文本的开始和结束索引。
所以得到这样的文字。
String title=str.subString(start,end);
为什么不创建一个 MyFile
class 来为您进行解析,将键值对存储在 Map<String, String>
中,然后您可以访问它。这将使您的代码更具可读性,并且更易于维护。
类似于以下内容:
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();
}
}
这将首先解析整个文件。文件的预期格式为:
0 ... 59
[KEY][WHITE SPACE][VALUE]
0 ... 59
[WHITE SPACE][VALUE TO APPEND TO PREVIOUS KEY]
这允许可变长度的密钥。
允许您单独处理异常,然后像这样轻松引用文件的内容:
MyFile journalFile = new MyFile("text.txt");
try {
journalFile.parse();
} catch (IOException e) {
System.err.println("Malformed file");
e.printStackTrace();
}
jTextField2.setText(journalFile.getEntry("TITLE"));
我正在使用以下代码将文本文件内容加载到 GUI:
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
我收到这条线:"Sound, mobility and landscapes of exhibition: radio-guided"。
问题是我不知道如何到达 jTextField2
下一行的字符串 "tours at the Science Museum".
我想问一下如何在 jTextField2
上获得两条线,即 "Sound, mobility and landscapes of exhibition: radio-guided tours at the Science Museum"?
提前感谢您的帮助。
如果您使用 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"));
}
第一列是键。当密钥不存在时,使用最后一个密钥。 Map
用于存储键和值。当键已经存在时,该值通过连接与现有的值合并。
此代码输出预期的字符串:Sound, mobility and landscapes of exhibition: radio-guidedtours at the Science Museum
。
编辑: 对于 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"));
}
第一列为空(所有空格)表示该行是前一行的延续。所以你可以缓冲这些行并重复连接它们,直到你得到一个非空的第一列,然后 write/print 整行。
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) ;
}
你可以做到
首先将整个文件读入一个字符串对象。
然后获取 TITLE 和 AUTHOR 的索引
喜欢 int start=str.indexOf("TITLE"); and int end=str.indexOf("AUTHOR");
然后将 TITLE 的长度添加到起始索引 start+="TITLE".length();
并从结束索引中减去 AUTHOR 的长度 end-="AUTHOR".length();
最后你有了你想要的文本的开始和结束索引。
所以得到这样的文字。
String title=str.subString(start,end);
为什么不创建一个 MyFile
class 来为您进行解析,将键值对存储在 Map<String, String>
中,然后您可以访问它。这将使您的代码更具可读性,并且更易于维护。
类似于以下内容:
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();
}
}
这将首先解析整个文件。文件的预期格式为:
0 ... 59
[KEY][WHITE SPACE][VALUE]
0 ... 59
[WHITE SPACE][VALUE TO APPEND TO PREVIOUS KEY]
这允许可变长度的密钥。
允许您单独处理异常,然后像这样轻松引用文件的内容:
MyFile journalFile = new MyFile("text.txt");
try {
journalFile.parse();
} catch (IOException e) {
System.err.println("Malformed file");
e.printStackTrace();
}
jTextField2.setText(journalFile.getEntry("TITLE"));