简体   繁体   English

从文本文件中读取和查找字符串

[英]read and find string from text file

I am loading text file contents to GUI using this code: 我正在使用以下代码将文本文件内容加载到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) {
}

Then contents of text.txt file: 然后是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

On jTextField2 I am getting this line: "Sound, mobility and landscapes of exhibition: radio-guided" . jTextField2我得到以下一行: “声音,展览的流动性和风景:无线电引导” 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 ie "Sound, mobility and landscapes of exhibition: radio-guided tours at the Science Museum" ? 我想问一下如何在jTextField2上同时显示“声音,流动性和展览景观:科学馆的无线电导览”吗?

Thank you in advance for any help. 预先感谢您的任何帮助。

If you are using Java 8 and assuming that the columns have a fixed number of characters, you could something like this: 如果您使用的是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"));
}

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. Map用于存储键和值。 When the key already exist, the value is merged with the existing one by concatenation. 当键已经存在时,该值将通过串联与现有键合并。

This code outputs the expected String: Sound, mobility and landscapes of exhibition: radio-guidedtours at the Science Museum . 此代码输出预期的字符串: Sound, mobility and landscapes of exhibition: radio-guidedtours at the Science Museum

EDIT: For Java 7 编辑:对于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"));
}

Why not create a MyFile class that does the parsing for you, storing key-value-pairs in a Map<String, String> , which you can then access. 为什么不创建一个为您执行解析的MyFile类,将键值对存储在Map<String, String> ,然后您可以访问它。 This will make your code more readable and will be easier to maintain. 这将使您的代码更具可读性,并且更易于维护。

Something like the following: 类似于以下内容:

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();
    }
}

This will parse the entire file first. 这将首先解析整个文件。 The expected format of the file is: 该文件的预期格式为:

0 ... 59
[KEY][WHITE SPACE][VALUE]
0 ... 59
[WHITE SPACE][VALUE TO APPEND TO PREVIOUS KEY]

This allows for variable length keys. 这允许使用可变长度的密钥。

Allowing you to handle exceptions separately, and then easily reference the contents of the file like so: 允许您分别处理异常,然后轻松引用文件内容,如下所示:

MyFile journalFile = new MyFile("text.txt");
try {
    journalFile.parse();
} catch (IOException e) {
    System.err.println("Malformed file");
    e.printStackTrace();
}

jTextField2.setText(journalFile.getEntry("TITLE"));

An empty (all spaces) first column indicates that a line is the continuation of the previous one. 第一列为空(所有空格)表示一行是前一行的延续。 So you can buffer the lines and repeatedly concatenate them, until you get a non-empty first column, and then write/print the whole line. 因此,您可以缓冲行并重复将它们连接起来,直到获得非空的第一列,然后再写/打印整行。

    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) ;
    }

you can do this First of all read the entire file into a string object. 您可以这样做首先将整个文件读入一个字符串对象。 then get the indexes of the TITLE and AUTHOR like int start=str.indexOf("TITLE"); and int end=str.indexOf("AUTHOR"); 然后像int start=str.indexOf("TITLE"); and int end=str.indexOf("AUTHOR");一样获得TITLE和AUTHOR的索引int start=str.indexOf("TITLE"); and int end=str.indexOf("AUTHOR"); int start=str.indexOf("TITLE"); and int end=str.indexOf("AUTHOR"); then add the length of TITLE into start index start+="TITLE".length(); 然后将TITLE的长度添加到开始索引start+="TITLE".length(); and subtract the length of AUTHOR from end index end-="AUTHOR".length(); 并从结束索引end-="AUTHOR".length();减去AUTHOR的长度end-="AUTHOR".length(); at last you have the start and end index of text that you want. 最后,您有了想要的文本的开始和结束索引。 so get the text like. 所以得到像这样的文字。

String title=str.subString(start,end);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM