检查 java 中的两个不同文件并进行比较

check two different files in java and compare them

我有两个文件。第一个是 属性 文件,第二个是内容文件

第一个文件

properties

{

"rowcount" : "3"

"delim" : "|"

}

第二个文件

a|b|c

d|e|f

g|h|i

我想读取两个文件并检查第二个文件是否符合规则。(第一个文件的结构总是相似的)

对于第一部分,只需读入第一个文件中的 rowcount 数字,然后与第二个文件中的 line count 进行比较。

对于第二部分,请阅读 delim,然后使用 Scanner 或类似于 read the second file using delim as your delimiter。如果您只想在每个分隔符之间插入一个字符,那么在读取文件时对此进行测试,如果您看到多个字符被读入,则抛出异常。

来自示例link:

import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;

public class MainClass {
  public static void main(String args[]) throws IOException {

    char[] chars = new char[100]; //If you know how many you want to read
    //(if not, use an ArrayList or similar)

    FileReader fin = new FileReader("Test.txt");
    Scanner src = new Scanner(fin);

    // Set delimiters to newline and pipe ("|")
    //Use newline character OR (bitwise OR is "|") pipe "|" character
    //since pipe is also OR (thus a meta character), you must escape it (double backslash)
    src.useDelimiter(src.useDelimiter(System.getProperty("line.separator")+"|\|");
    // Read chars
    for(int i = 0; src.hasNext(); i++) {
        String temp = src.next();
        if(temp.length != 1)
            System.out.println("Error, non char"); //Deal with as you see fit
        chars[i] = temp.charAt(0); //Get first (and only) character of temp
    }
    fin.close();
    //At this point, chars should hold all your data
  }
}

嗯,首先我认为第一个文件应该是 properties.json,语法如下:

{
    properties: {
        rowcount: "3",
        delim: "|" 
    }
}

使用 JSONParser 您可以读取 JSON 文件并将其映射到 Object

然后用FileReader你可以处理第二个文件。对于验证部分,我认为来自 FileReader 的正则表达式和 rowcount 可以轻松解决问题。