How can you put a collection in a file?



  • public static void main(String[] args) throws FileNotFoundException, IOException {
        String s;
        String s2;
        Scanner input = new Scanner(new File("C:\\qq.txt"));
        s = input.nextLine();
        s2 = input.nextLine();
    
        List<String> l1 = Arrays.asList(s.split(""));
        List<String> l2 = Arrays.asList(s2.split(""));
        Set<String> result = new LinkedHashSet<>();
        result.addAll(l1);
        result.addAll(l2);
        result.retainAll(l1);
        result.retainAll(l2);
        System.out.println(result);
    }
    

    Here's the code for Java. He's turning the results into a program, how can it be possible to make a withdrawal in .txt?



  • Replace. System.out.println(result); to the next code and you'll get a similar conclusion to the file. out.txt For consoles:

            try(FileWriter writer = new FileWriter("C:\\out.txt")) {
                writer.write(result.toString());
                writer.flush();
            }
    

    If you need to put the collection elements in the file fast, use the cycle:

            try(FileWriter writer = new FileWriter("C:\\out.txt")) {
                for (String s : set)
                    writer.write(s + '\n');
                writer.flush();
            }
    

Log in to reply
 

Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2