Reputation: 45
I'm trying to write my java console output to a .txt file in my desktop. But when that method starts, i have the console output and the txt file gets created, but it's empty and I realized that the BufferedReader (in) is not working... (Because of the "ok1 - i" statement)
The question is WHY?? or WHAT'S WRONG WITH MY CODE?? This is my code, so you can see and run it
package noobxd;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Random;
public class Main {
public static void main(String[] args) throws IOException {
String path = "C:\\Users\\Mario\\Desktop\\output.txt";
generate_codes();
writetxt(path);
}
private static void writetxt(String path) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter out = new BufferedWriter(new FileWriter(path));
try {
String inputLine;
inputLine = "";
int i=0;
System.out.println("Starting");
while (!inputLine.isEmpty()){
System.out.println("ok1"+i);
inputLine = in.readLine();
System.out.println("ok2"+i);
out.write(inputLine);
System.out.println("ok3"+i);
out.newLine();
System.out.println("ok4"+i);
i++;
}
System.out.print("Write Successful");
} catch (IOException e1) {
System.out.println("Error during reading/writing");
} finally {
out.close();
in.close();
}
}
private static void generate_codes() {
Random rnd = new Random();
for (int i = 0; i < 30; i++) {
int code = rnd.nextInt(201) + 100;
int students = rnd.nextInt(31) + 40;
int j = rnd.nextInt(4);
String type = new String();
switch (j) {
case 0:
type = "Theory";
break;
case 1:
type = "Lab";
break;
case 2:
type = "Practice";
break;
case 3:
type = "Exam";
break;
}
System.out.println("TEL" + code + "-TopicNumber" + i + "-" + students + "-" + type);
}
}
}
Thanks for your time, please help me solve my problem.
Upvotes: 0
Views: 1078
Reputation: 6230
String inputLine;
inputLine = "";
...
while (!inputLine.isEmpty()) // this is false and so the loop is not executed
In the future, please learn to use debugging tools and simply read your code more carefully. If you're trying to read until EOF, use
while ((inputLine = in.readLine()) != null) {
...
}
Upvotes: 2
Reputation: 5134
You probable should do something like this:
inputLine = in.readLine();
while (inputLine != null && !inputLine.isEmpty()){
System.out.println("ok1"+i);
System.out.println("ok2"+i);
out.write(inputLine);
System.out.println("ok3"+i);
out.newLine();
System.out.println("ok4"+i);
i++;
inputLine = in.readLine();
}
Upvotes: 0
Reputation: 31689
If you want to keep looping until the user enters an empty line at the console, you probably want something like
while (true) {
System.out.println("ok1"+i);
inputLine = in.readLine();
if (inputLine.isEmpty())
break;
// the rest of your loop
}
Upvotes: 0