Sarah Mohamed
Sarah Mohamed

Reputation: 33

Write to files using Java

I am trying to use lists for my first time, I have a txt file that I am searching in it about string then I must write the result of searching in new file.

Check the image attachedenter image description here

My task is to retrieve the two checked lines of the input file to the output files.

And this is my code:

import java.io.*;
import java.util.Scanner;

public class TestingReport1 {
public static void main(String[] args) throws Exception {

    File test = new File("E:\\test2.txt");
    File Result = new File("E:\\Result.txt");

    Scanner scanner = new Scanner(test);
    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();
        if(line.contains("Visit Count")|| line.contains("Title")) {
           System.out.println(line);
        }
    }
}
}

What should I do?!

Edit: How can I write the result of this code into text file? Edit2:

Now using the following code:

    public static void main(String[] args) throws Exception {
    // TODO code application logic here

    File test = new File("E:\\test2.txt");
    FileOutputStream Result = new FileOutputStream("E:\\Result.txt");

    Scanner scanner = new Scanner(test);
    while (scanner.hasNextLine()) {
        String line = scanner.nextLine();
        if(line.contains("Visit Count")|| line.contains("Title")) {
           System.out.println(line);
           Files.write(Paths.get("E:\\Result.txt"), line.getBytes(), StandardOpenOption.APPEND);
       }
    }
}

I got the result back as Visit Count:1 , and I want to get this number back as integer, Is it possible?

Upvotes: 0

Views: 87

Answers (1)

beatngu13
beatngu13

Reputation: 9373

Have a look at Files, especially readAllLines as well as write. Filter the input between those two method calls, that's it:

// Read.
List<String> input = Files.readAllLines(Paths.get("E:\\test2.txt"));
// Filter.
String output = input.stream()
        .filter(line -> line.matches("^(Title.*|Visit Count.*)"))
        .collect(Collectors.joining("\n"));
// Write.
Files.write(Paths.get("E:\\Result.txt"), output.getBytes());

Upvotes: 1

Related Questions