从文本文件

时间:2016-05-10 05:01:37

标签: 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(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上获得两条线,即“声音,移动性和展览风景:科学博物馆的无线电导游”

提前感谢您的帮助。

4 个答案:

答案 0 :(得分:1)

如果您使用的是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"));
}

答案 1 :(得分:1)

为什么不创建一个MyFile类来为您解析,将键值对存储在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"));

答案 2 :(得分:0)

空(所有空格)第一列表示一行是前一行的延续。因此,您可以缓冲行并重复连接它们,直到获得非空的第一列,然后写入/打印整行。

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

答案 3 :(得分:0)

你可以这样做 首先将整个文件读入一个字符串对象。 然后获取TITLE和AUTHOR的索引 像int start=str.indexOf("TITLE"); and int end=str.indexOf("AUTHOR"); 然后将TITLE的长度添加到起始索引start+="TITLE".length(); 并从结束索引end-="AUTHOR".length();中减去AUTHOR的长度 最后你有你想要的文本的开始和结束索引。 所以得到文字就好。

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