Reputation: 59
Here in this code some operations are done with using one file (new.txt) I want to store the output of below code in another file....
public static void main(String a[]) throws Exception {
try {
Arrays.stream(Files.lines(Paths.get("new.txt")).collect(Collectors.joining())
.replaceAll("^.*?1002|1003(.(?!1002))*$", "\n") // trim leading/trailing non-data
.split("1003.*?1002")) // split on end-to-start-of-next
.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
}
Upvotes: 3
Views: 198
Reputation: 109567
As you already kept the entire file contents in memory, a non-stream solution is more straight-forward.
String txt = new String(Files.readAllBytes(Paths.get("in.txt")), StandardCharsets.UTF_8);
txt = txt.replaceAll(...);
txt = txt.replaceAll(...); // split behavior
Files.write(Paths.get("out.txt"), txt.getBytes(StandardCharsets.UTF_8));
Added: Though the logic escapes me, the replacements probably should be:
finale String EOL = "\n";
txt = txt.replaceAll("^.*?1002|1003(.(?!1002))*$", EOL ) // trim leading/trailing non-data
txt = txt.replaceAll("1003.*?1002", EOL ) // split on end-to-start-of-next
Upvotes: 3
Reputation: 13551
You could try that:
public static void main(String a[]) throws Exception
{
try {
PrintWriter os = new PrintWriter("output.txt");
Arrays.stream(Files.lines(Paths.get("new.txt")).collect(Collectors.joining())
.replaceAll("^.*?1002|1003(.(?!1002))*$", "\n") // trim leading/trailing non-data
.split("1003.*?1002")) // split on end-to-start-of-next
.forEachOrdered(os::println);
}
catch (IOException e)
{
e.printStackTrace();
}
}
Upvotes: 2
Reputation: 1409
No sure what exactly are you looking for. Here is one way of doing it and what I would do.
You can do this directly from the terminal
javac myFile.java
java ClassName > myfile.txt
This would save your output into a file 'myfile.txt'
Upvotes: 0