簡體   English   中英

如何使用java解析文本文件以在另一個文本文件中寫入某些行?

[英]How do I parse a text file to write certain lines in another text file using java?

我正在學習如何使用 Java 處理文件。 我有一個包含密鑰對及其值的示例文件。 我正在嘗試查找密鑰對,如果匹配,則輸出文件將同時更新密鑰對及其值。 我能夠在輸出文件中獲取密鑰對,但也無法獲取值。 Stringbuilder 可能在這里工作來附加字符串,但我不知道如何。

下面是我的輸入和輸出文件。

Input File:

born time 9 AM London -- kingNumber 1234567890 -- address: abc/cd/ef -- birthmonth: unknown
born time 9 AM Europe -- kingNumber 1234567890 -- address: abc/cd/ef -- birthmonth: december

Expected Output File:

kingNumber 1234567890 birthmonth unknown 
kingNumber 1234567890 birthmonth unkbown

Current Output File:

kingNumber birthmonth 
kingNumber birthmonth

我能夠將密鑰對(在這種情況下為“kingNumber”和“birthmonth”)寫入輸出文件,但我不確定我能做些什么來獲得它的價值。

    String kn = "kingNumber:";
    String bd = "birthmonth:";

    try {

        File f = new File("sample.txt");
        Scanner sc = new Scanner(f);
        FileWriter fw = new FileWriter("output.txt");


        while(sc.hasNextLine()) {
            String lineContains = sc.next();
            if(lineContains.contains(kn)) {
                fw.write(kn  + "\n");
                // This is where I am stuck. What
                // can I do to get it's value (number in this case).
            }
            else if(lineContains.contains(bd)) {
                fw.write(bd);
                // This is where I am stuck. What
                // can I do to get it's value (birthday in this case).
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

我編寫了一個簡單的解析器,它遵循您示例中的數據格式。 你需要這樣稱呼它:

PairParser parser = new PairParser(lineContains);

那么你可以通過對鍵從解析器中獲取值如何獲取值:

parser.getValue("kingNumber")

請注意,鍵沒有尾隨列字符。

解析器代碼在這里:

package com.grenader.example;

import java.util.HashMap;
import java.util.Map;

public class PairParser {

    private Map<String, String> data = new HashMap<>();

    /**
     * Constructor, prepare the data
     * @param dataString line from the given data file
     */
    public PairParser(String dataString) {
        if (dataString == null || dataString.isEmpty())
            throw new IllegalArgumentException("Data line cannot be empty");

        // Spit the input line into array of string blocks based on '--' as a separator
        String[] blocks = dataString.split("--");

        for (String block : blocks)
        {
            if (block.startsWith("born time")) // skip this one because it doesn't looks like a key/value pair
                continue;
            String[] strings = block.split("\\s");
            if (strings.length != 3) // has not exactly 3 items (first items is empty), skipping this one as well
                continue;
            String key = strings[1];
            String value = strings[2];
            if (key.endsWith(":"))
                key = key.substring(0, key.length()-1).trim();

            data.put(key.trim(), value.trim());
        }
    }

    /**
     * Return value based on key
     * @param key
     * @return
     */
    public String getValue(String key)
    {
        return data.get(key);
    }

    /**
     * Return number of key/value pairs
     * @return
     */
    public int size()
    {
        return data.size();
    }
}

這是單元測試以確保代碼有效

package com.grenader.example;

import com.grenader.example.PairParser;
import org.junit.Test;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;

public class PairParserTest {

    @Test
    public void getValue_Ok() {
        PairParser parser = new PairParser("born time 9 AM London -- kingNumber 1234567890 -- address: abc/cd/ef -- birthmonth: unknown");

        assertEquals("1234567890", parser.getValue("kingNumber"));
        assertEquals("unknown", parser.getValue("birthmonth"));
    }

    @Test(expected = IllegalArgumentException.class)
    public void getValue_Null() {
        new PairParser(null);
        fail("This test should fail with Exception");
    }

    @Test(expected = IllegalArgumentException.class)
    public void getValue_EmptyLine() {
        new PairParser("");
        fail("This test should fail with Exception");
    }

    @Test()
    public void getValue_BadData() {
        PairParser parser = new PairParser("bad data bad data");
        assertEquals(0, parser.size());

    }
}

你可以使用java.util.regex.Pattern & java.util.regex.Matcher與模式類似:

^born\stime\s([a-zA-Z0-9\s]*)\s--\skingNumber\s(\d+)\s--\saddress:\s([a-zA-Z0-9\s/]*)\s--\sbirthmonth:\s([a-zA-Z0-9\s]*)$

少寫,多做。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM