Click here to Skip to main content
15,921,530 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
input file---hello.txt file
hello
java
hello
java
output file--xyz.txt file
hello
java

What I have tried:

Java
public static void main(String[] args) throws IOException 
    {
        // PrintWriter object for output.txt
        PrintWriter pw = new PrintWriter("output.txt");
         
        // BufferedReader object for input.txt
        BufferedReader br1 = new BufferedReader(new FileReader("input.txt"));
         
        String line1 = br1.readLine();
         
        // loop for each line of input.txt
        while(line1 != null)
        {
            boolean flag = false;
             
            // BufferedReader object for output.txt
            BufferedReader br2 = new BufferedReader(new FileReader("output.txt"));
             
            String line2 = br2.readLine();
             
            // loop for each line of output.txt
            while(line2 != null)
            {
                 
                if(line1.equals(line2))
                {
                    flag = true;
                    break;
                }
                 
                line2 = br2.readLine();
             
            }
             
            // if flag = false
            // write line of input.txt to output.txt
            if(!flag){
                pw.println(line1);
                 
                // flushing is important here
                pw.flush();
            }
             
            line1 = br1.readLine();
             
        }
         
        // closing resources
        br1.close();
        pw.close();
         
        System.out.println("File operation performed successfully");
    }
}
Posted
Updated 17-Jul-18 7:23am
v2

1 solution

Java has means of removing duplicates, if double-loop isn't a requirement...
Java
String[] szInput = {"input file---hello.txt file", "hello", "java", "hello", "java", "output file--xyz.txt file", "hello", "java"}; // you create it by reading all lines of the input file!!!
Set<String> szSet = new HashSet<String>(Arrays.asList(szInput)); // the same string will create the same hash so duplicates will be removed...
String[] szOutput = szSet.toArray(new String[szSet.size()]); // write to output file
 
Share this answer
 
Comments
CPallini 27-Sep-17 6:35am    
Probably a LinkedHashSet is better suited for the purpose.
My 5.
Kornfeld Eliyahu Peter 27-Sep-17 6:36am    
In case the order is important...
Thank you!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900