简体   繁体   中英

How can I combine two classes?

I have two .txt files. Firstly, I put the contents of file1.txt into string array. After that, I use another class to do the same thing for another file: file2.txt . I then compare contents of the two string array's against each other (specifically the words in the string arrays.) How can I combine my two classes each other?

Welcome to SO,

There is no point mixing DataInputStream and BufferedReader. A simpler pattern is to do the following

can I compare these contents of two txt files?

public static void main(String... args) throws IOException {
    List<String> strings1 = readFileAsList("D:\\Denemeler\\file1.txt");
    List<String> strings2 = readFileAsList("D:\\Denemeler\\file2.txt");
    compare(strings1, strings2);
}

private static void compare(List<String> strings1, List<String> strings2) {
    // TODO
}

private static List<String> readFileAsList(String name) throws IOException {
    List<String> ret = new ArrayList<String>();
    BufferedReader br = null;
    try {
        br = new BufferedReader(new FileReader(name));
        String strLine;
        while ((strLine = br.readLine()) != null)
            ret.add(strLine);
        return ret;
    } finally {
        if (br != null) br.close();
    }
}

You want to perform all these operations in one program. One program have only one active method main that will be executed when you start program.

  • Read file1.txt into string array
  • Read file2.txt into string array
  • Compare the results

your main method will looks like:

public static void main(String[] args) {
   String[] s1 = read("file1.txt");
   String[] s2 = read("file2.txt");
   compare(s1, s2);
}

Now you implement method String[] read(File f) with your own logic and comaprison in method compare(String[] s1, String[] s2)

Jes 'Peter Lawrey' is right.

Java is an object oriented program we have to keep that in mind. use a common method and avoid one class.

if you want to know about the inner class have a look at this Java Inner class

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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