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 attached
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?
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());
Related
I am new to Java, and I am learning how to read input using Java on Eclipse. I am using a scanner to read a .txt input file, however, it doesn't seem to be reading the very first integer in the .txt file.
Here is the .txt file:
2 1 4
Here is my simplified code:
public class Test {
static int var;
static int[] arr;
public static void main(String[] args) {
String fileName = "/Users/anon/eclipse-workspace/Lab/src/input-01.txt";
readInput(fileName);
}
public static void readInput(String fileName) {
File file = new File(fileName);
Scanner fileInput = new Scanner(file);
//Read T
var = fileInput.nextInt();
System.out.printf("var: %d", var);
arr = new int[var];
}
I tried debugging, and I realized that "int var" never even appeared in the variables table on the right -- so I am not sure if "int var" was even initialized at all.
Please let me know if there are any other information that I can provide, and thank you in advance for you help and advices.
Check the input file contents. It could be a problem.
import java.io.File;
import java.util.Scanner;
public class Sample {
public static void main(String[] args) throws Exception {
String fileName = "src/main/resources/input-01.txt";
readInput(fileName);
}
public static void readInput(String fileName) throws Exception {
File file = new File(fileName);
Scanner fileInput = new Scanner(file);
//Read T
int var = fileInput.nextInt();
System.out.println("var = " + var);
}
}
input-01.txt file content
10 sampletext
output
var = 10
Process finished with exit code 0
I am quite new to java, so it might be a stupid question. But I need it to be solved for my data structure class project...
So I am trying to feed my program with 2 different input files. I know we can use Scanner and InputStreamReader to achieve this with 1 file, I don't know how I should do it with 2 files.
In some answers to similar questions with mine, someone mentioned shell which I think can probably solve this problem. However, I don't know anything about shell, so I am wondering if this problem can be solved without writing a shell file, and what the syntax would be for inputting multiple files in command line.
What I execute in command line(with 1 input file):
java UserInterfaceOrNot < input.txt > output.txt
I will post more code if needed.
Code:
public class UserInterfaceOrNot
{
public static EventManager em;
public static Scanner scn = new Scanner(new InputStreamReader(System.in));
public static void main (String [] args)
{
UserInterfaceOrNot ui = new UserInterfaceOrNot();
while (scn.hasNext()){ui.runData();}
scn = new Scanner(new InputStreamReader(System.in));
while (scn.hasNext() && !scn.next().equals("x")){ui.runCommand();}
}
java UserInterfaceOrNot input1.txt input2.txt output.txt
When you call your program as this, you're actually passing 3 arguments to your java public static void main (String [] args) method.
You can find these argument in order in that String array (String [] args).
To read the arguments:
String myFirstFile = args[0]; // this will be "input1.txt"
String mySecondFile = args[1]; // this will be "input2.txt"
String myOutputFile = args[2]; // this will be "output.txt"
You can read each file (input1 and input2) like this by creating another method
public String readFileAsString(String inputFile) throw IOException {
BufferedReader br = new BufferedReader(new FileReader(inputFile));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
return sb.toString();
} finally {
br.close();
}
}
Then in your main method you can call it like this:
public static void main(String[] args) throws Exception {
UserInterfaceOrNot ui = new UserInterfaceOrNot();
String inputFile1 = args[0];
String inputFile2 = args[1];
String input1AsString = ui.readFileAsString(inputFile1);
String input2AsString = ui.readFileAsString(inputFile2);
//continue with your logic
}
How do I read the following information from a txt file and write just the numbers to another text file using Java? I have it displaying to the console but it will not write to the file also.
Jones 369218658389641
Smith 6011781008881301
Wayne 5551066751345482
Wines 4809134775860430
Biggie 9925689541232325
Luke 7586425896325410
Brandy 4388576018410707
Ryan 2458912425860439
import java.util.Scanner;
import java.io.File;
public class test {
public static void main(String[] args) throws Exception {
// Create a File instance
java.io.File file = new java.io.File("accounts.txt");
// Create a Scanner for the file
Scanner input = new Scanner(file);
// Read data from a file
while (input.hasNext()) {
String accountName = input.next();
Long cardNumber = input.nextLong();
//this is where I want to write just the numbers to a file called cardnums.txt
file = new java.io.File("cardnums.txt");
java.io.PrintWriter output = new java.io.PrintWriter(file);
output.println(cardNumber);
System.out.println(cardNumber);
}
// Close the file
input.close();
}
}
I got it now.
import java.util.Scanner;
import java.io.File;
public class test {
public static void main(String[] args) throws Exception {
// Create a File instance
java.io.File file = new java.io.File("accounts.txt");
// Create a Scanner for the file
Scanner input = new Scanner(file);
// Read data from a file
file = new java.io.File("cardnums.txt");
java.io.PrintWriter output = new java.io.PrintWriter(file);
while (input.hasNext()) {
String accountName = input.next();
Long cardNumber = input.nextLong();
//this is where I want to write just the numbers to a file called credit.txt
output.println(cardNumber);
System.out.println(cardNumber);
}
// Close the file
input.close();
output.flush();
output.close();
}
}
java.io.PrintWriter output = new java.io.PrintWriter(file);
First of all why are you everytime calling this in loop with same filename?
Secondly, once you define it outside loop,
Call flush() on outputstream object and close if not null (preferabbly in finally block) after loop.
if(output!=null) {
output.flush();
output.close();
}
Here's a 1-liner:
Files.write(Paths.get("cardnums.txt"), () ->
Files.lines(Paths.get("accounts.txt"))
.map(s -> s.replaceAll("\\D", ""))
.collect(toList())
.iterator());
Disclaimer: Code may not compile or work as it was thumbed in on my phone (but there's a reasonable chance it will work)
I'm designing a program to split data stored in a text file into two separate files based on the label of that data.
Here is a small version of that data.
0,1,2,normal.
5,5,5,strange.
2,1,3,normal.
I use a class to store each line as a sample. The class parses the line to store the last value as the label. I encapsulated each line as an object, because I intend to add features later.
Here is code for the Sample class
import java.util.Scanner;
public class Sample {
String[]str_vals = new String[3];
String label;
Sample(Scanner line) {
for (int i=0; i<3; i++) {
str_vals[i] = line.next();
}
label = line.next();
}
String getValsForCSV() {
StringBuilder retval = new StringBuilder();
for (int i=0; i<3; i++) {
retval.append(str_vals[i]).append(",");
}
retval.append(label).append(".");
return retval+"";
}
String getLabel() {
return label;
}
}
Below is the code in question. My Separator class.
import java.io.*;
import java.util.Scanner;
public class Separator {
public static final String DATAFILE = "src/etc/test.txt";
public static void main(String[] args) throws FileNotFoundException {
runData();
}
public static void runData() throws FileNotFoundException {
try (Scanner in = new Scanner(new File(DATAFILE))) {
// kddcup file uses '.\n' at end of each line
// setting this as delimiter which will consume the period
in.useDelimiter("[.]\r\n|[.]\n|\n");
Sample curr;
while(in.hasNext()) {
// line will hold all fields for a single sample
Scanner line = new Scanner(in.next());
line.useDelimiter(", *");
curr = new Sample(line);
try (
PrintWriter positive = new PrintWriter(new File(DATAFILE+"-pos"));
PrintWriter negative = new PrintWriter(new File(DATAFILE+"-neg"));
) {
if (curr.getLabel().equals("normal")) {
positive.println("GOOD");
} else {
negative.println("BAD");
}
}
}
}
}
}
This issue that I am experiencing is that the code only saves the last Sample seen to its respective file. So with above data the test.txt-neg will be empty and test.txt-pos will have a single line GOOD; it does not have two GOOD's as expected.
If I modify the test.txt data to include only the first two lines, then the files states are reversed (i.e. test.txt-neg has BAD and test.txt-pos is empty). Could someone please explain to me what is going on, and how to fix this error?
Because the error was pointed out in a comment. I wanted to give credit to KevinO and Elliott Frisch for the solution.
As mentioned, I'm creating a new PrintWriter each time and creating the PrintWriter in it's default mode of overwriting a file. As a result it always saves both files based on a single sample.
To correct this error, I have pulled out the instantiations of the PrintWriter to be in the try-with-resource block of the Scanner object
import java.io.*;
import java.util.Scanner;
public class Separator {
public static final String DATAFILE = "src/etc/test.txt";
public static void main(String[] args) throws FileNotFoundException {
runData();
}
public static void runData() throws FileNotFoundException {
try (
Scanner in = new Scanner(new File(DATAFILE));
PrintWriter positive = new PrintWriter(new File(DATAFILE+"-pos"));
PrintWriter negative = new PrintWriter(new File(DATAFILE+"-neg"));
) {
// kddcup file uses '.\n' at end of each line
// setting this as delimiter which will consume the period
in.useDelimiter("[.]\r\n|[.]\n|\n");
Sample curr;
while(in.hasNext()) {
// line will hold all fields for a single sample
Scanner line = new Scanner(in.next());
line.useDelimiter(", *");
curr = new Sample(line);
if (curr.getLabel().equals("normal")) {
positive.println("GOOD");
} else {
negative.println("BAD");
}
}
}
}
}
Is it possible to create a Java program which recognizes the text in a .txt file and write it in a .csv file? If yes,how would you start with such a problem?
My .txt file is Text1 |Text 2 so I could somehow get the char "|" and split it into two cells.
This is very simple in Java 8:
public static void main(String[] args) throws Exception {
final Path path = Paths.get("path", "to", "folder");
final Path txt = path.resolve("myFile.txt");
final Path csv = path.resolve("myFile.csv");
try (
final Stream<String> lines = Files.lines(txt);
final PrintWriter pw = new PrintWriter(Files.newBufferedWriter(csv, StandardOpenOption.CREATE_NEW))) {
lines.map((line) -> line.split("\\|")).
map((line) -> Stream.of(line).collect(Collectors.joining(","))).
forEach(pw::println);
}
}
First you get your files at Path objects.
Then you open a PrintWriter to your destination Path.
Now you do some Java 8 stream processing with lambdas:
Files.lines(txt) streams the lines from the file
map((line) -> line.split("\\|")) splits each line to a String[] on |
map((line) -> Stream.of(line).collect(Collectors.joining(","))) joins the individual String[] again using ,
forEach(pw::println) writes the new lines to the destination file.
Using import static:
try (
final Stream<String> lines = Files.lines(txt);
final PrintWriter pw = new PrintWriter(newBufferedWriter(csv, StandardOpenOption.CREATE_NEW))) {
lines.map((line) -> line.split("\\|")).
map((line) -> Stream.of(line).collect(joining(","))).
forEach(pw::println);
}
As Java 8 was released only yesterday here is a Java 7 solution:
public static void main(String[] args) throws Exception {
final Path path = Paths.get("path", "to", "folder");
final Path txt = path.resolve("myFile.txt");
final Path csv = path.resolve("myFile.csv");
final Charset utf8 = Charset.forName("UTF-8");
try (
final Scanner scanner = new Scanner(Files.newBufferedReader(txt, utf8));
final PrintWriter pw = new PrintWriter(Files.newBufferedWriter(csv, utf8, StandardOpenOption.CREATE_NEW))) {
while (scanner.hasNextLine()) {
pw.println(scanner.nextLine().replace('|', ','));
}
}
}
Again, with import static:
try (
final Scanner scanner = new Scanner(newBufferedReader(txt, utf8));
final PrintWriter pw = new PrintWriter(newBufferedWriter(csv, utf8, StandardOpenOption.CREATE_NEW))) {
while (scanner.hasNextLine()) {
pw.println(scanner.nextLine().replace('|', ','));
}
}
Yes it is very much possible.
Replace | by , and
write it to a csv
public class NewClass {
public static void main(String[] args) throws IOException {
String data = "one|two|three|four"+"\n"+
"one|two|three|four";
//Use a BufferedReader to read from actual Text file
String csv = data.replace("|", ",");
System.out.println(csv);
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("MyCSV.csv")));
out.println(csv);
out.close();
}
}
Output
run:
one,two,three,four
one,two,three,four
BUILD SUCCESSFUL (total time: 0 seconds)
You first need to How do I create a Java string from the contents of a file?.
Then you can take advantage of How to split a string in Java and use | as the delimiter.
As the last step you can use the Joiner to create the final String and store it using How do I save a String to a text file using Java?.
Yes it is possible. To accomplish your task read about Input- and OutputStreams.
Start with a simple example. Read a line of text from a file and print it out on the console.
Then do it the other way - write a line of text into a file.
The experience you get through these examples will help to accomplish your task.
try this may help
public class Test {
public static void main(String[] args) throws URISyntaxException,
IOException {
FileWriter writer = null;
File file = new File("d:/sample.txt");
Scanner scan = new Scanner(file);
File file2 = new File("d:/CSV.csv");
file.createNewFile();
writer = new FileWriter(file2);
while (scan.hasNext()) {
String csv = scan.nextLine().replace("|", ",");
System.out.println(csv);
writer.append(csv);
writer.append("\n");
writer.flush();
}
}
}
sample.txt:-
He|looked|for|a|book.
He|picked|up|the|book.
Commons CSV is useful for handling CSV output in your Java code too - in particular it takes care of gotchas such as quoting, etc:
http://commons.apache.org/proper/commons-csv/
Also commons IO is really useful for simplifying reading/writing files too:
https://commons.apache.org/proper/commons-io/description.html
HTH