Reputation: 3
I am trying to write some variables to a text file once a user has inputted some data. I have had it working before but I was tinkering with it and now it doesn't write to the text file at all. Here is the code:
try (PrintWriter out = new PrintWriter(new BufferedWriter(
new FileWriter("C:\\Users\\A612646\\workspace\\CarParkProject\\PrePaid.txt", true)))) {
if (AmountofHours < 0 || AmountofHours > 24) {
out.print(RegNo);
out.print("\t" + AmountofHours);
out.print("\t" + CreditCardNo);
out.print("\t" + expiry);
}
} catch (IOException e) {
e.printStackTrace();
}
Upvotes: 0
Views: 1466
Reputation: 413
There is nothing wrong with the code!. This code writes the data to the text file. Make sure your logic is correct as willow512 suggested. I would suggest you debug the code to narrow the cause.
public class TestFile {
public static void main(String[] args) {
int AmountofHours = 25;
int RegNo = 52431;
String CreditCardNo = "5315-XXXX-1456-XXXX";
String expiry = "15/25";
try (PrintWriter out = new PrintWriter(new BufferedWriter(
new FileWriter("C:\\Users\\thanigaiarasur\\workspace\\ExploreThings\\PrePaid.txt", true)))) {
if (AmountofHours < 0 || AmountofHours > 24) {
out.print(RegNo);
out.print("\t" + AmountofHours);
out.print("\t" + CreditCardNo);
out.print("\t" + expiry);
System.out.println("printed successfully");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Upvotes: 0
Reputation: 142
Are you sure the line:
if (AmountofHours < 0 || AmountofHours > 24)
should not be
if (AmountofHours > 0 && AmountofHours < 24)
You're saying if a car is parked less than 0 hours or more than 24 then write a line. I think you intend to say if a car is parked for longer than 0 hours and less than 24...
Upvotes: 3
Reputation: 1
looks like you are opening a Filewriter, but not the File itself.
try this:
File file = new File("C:\\Users\\A612646\\workspace\\CarParkProject\\PrePaid.txt");
if (!file.exists())
file.createNewFile(); //this creates the file :)
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
bw.write("content to write"); //here you will write you stuff
bw.close();
Upvotes: -2