Over writing to 2 files at the same time in java - java

I would like to write to 2 different txt files at the same time with the same data but currently i can over-write one file but the other, help guys??
if (choice.charAt(0) == 'y' || choice.charAt(0) == 'Y'){
credits = 10;
System.out.println("Redeemed! Congratulations! $1.00 worth of credits have been added to your account.");
int finalpoints = points - credits;
try {
FileWriter fw = new FileWriter("Transaction.history",true);
fw.write(firstname + ";" + Integer.toString(finalpoints) + ";" + "$1.00" + ";" + dateToPrintToFile + "\r\n");
fw.close();
}catch (IOException ee){
System.out.println("Input file not found!");
}
//int finalpoints1 = points - credits;
try {
FileWriter fw = new FileWriter("Points" , true);
fw.write(firstname + ";" + Integer.toString(point -credits));
fw.close();
}catch (IOException ee){
System.out.println("Input file not found!");
}
}

Related

Java file is blank when Writing in a file

Appreciate the help. I am using Java and I want to write a text in the file. I am not sure what is wrong with my code. Is below code sufficient since it is a snippets of the program? I am trying to write a text in the file and there is no error. When I tried opening the file, the file is blank.
PharmacyReceipt = is the file where the system will read it and compute the total price
PharmacyInvoice = if the money exceeds the total price, the system will write an invoice and delete the receipt file
Thank you
double change = 0;
grandTotal = 0;
try {
BufferedReader pharmacyFile = new BufferedReader(new FileReader("pharmacyReceipt.txt"));
BufferedWriter write1 = new BufferedWriter(new FileWriter("pharmacyInvoice.txt", true));
String input_1;
System.out.printf("%-16s %-50.30s %-20s %-20s %-20s\n", "Product Code", "Product Name", "Price", "Quantity", "Net Amount");
while ((input_1 = pharmacyFile.readLine()) != null) {
String[] data = input_1.split(",");
adminObject.setProductCode(data[0]);
adminObject.setName(data[1]);
adminObject.setPrice(Double.parseDouble(data[2]));
adminObject.setQuantity(Double.parseDouble(data[3]));
adminObject.setTax(Double.parseDouble(data[4]));
adminObject.setDiscount(Double.parseDouble(data[5]));
int MAX_CHAR = 40;
int maxLength = (adminObject.getName().length() < MAX_CHAR) ? adminObject.getName().length() : MAX_CHAR;
//grossAmount = adminObject.getPrice() * (adminObject.getTax()/100);
//netAmount = adminObject.getQuantity() * (grossAmount - (grossAmount * adminObject.getDiscount()/100));
netAmount = adminObject.getPrice() * adminObject.getQuantity();
System.out.printf("%-16s %-50.30s %-20.2f %-20.2f %.2f\n", adminObject.getProductCode(), adminObject.getName().substring(0, maxLength), adminObject.getPrice(), adminObject.getQuantity(), netAmount);
//System.out.println(adminObject.getProductCode() + "\t \t " + adminObject.getName() + "\t\t " + adminObject.getPrice() + "\t\t " + adminObject.getQuantity() + "\t\t " + adminObject.getTax() + "\t " + adminObject.getDiscount());
grandTotal += netAmount;
}
System.out.printf("\nGrand Total = PHP %.2f\n\n", grandTotal);
pharmacyFile.close();
System.out.print("Do you want to proceed to print the receipt? ");
choice_3 = sc.nextLine();
choice_3 = choice_3.toUpperCase();
if (choice_3.equals("YES") || choice_3.equals("Y")) {
System.out.print("\nHow much is the money? ");
double money = sc.nextDouble();
if (grandTotal <= money) {
BufferedReader groceryFile1 = new BufferedReader(new FileReader("pharmacyReceipt.txt"));
System.out.printf("%-16s %-50.30s %-20s %-15s %-20s\n", "Product Code", "Product Name", "Price", "Quantity", "Net Amount");
while ((input_1 = groceryFile1.readLine()) != null) {
String[] data = input_1.split(",");
adminObject.setProductCode(data[0]);
adminObject.setName(data[1]);
adminObject.setPrice(Double.parseDouble(data[2]));
adminObject.setQuantity(Double.parseDouble(data[3]));
adminObject.setTax(Double.parseDouble(data[4]));
adminObject.setDiscount(Double.parseDouble(data[5]));
int MAX_CHAR = 40;
int maxLength = (adminObject.getName().length() < MAX_CHAR) ? adminObject.getName().length() : MAX_CHAR;
//grossAmount = adminObject.getPrice() * (adminObject.getTax()/100);
//netAmount = adminObject.getQuantity() * (grossAmount - (grossAmount * adminObject.getDiscount()/100));
netAmount = adminObject.getPrice() * adminObject.getQuantity();
write1.write(adminObject.getProductCode() + "," + adminObject.getName() + "," + adminObject.getPrice() + "," + adminObject.getQuantity() + "," + adminObject.getTax() + "," + adminObject.getDiscount() + "," + adminObject.getTax() + "," + adminObject.getDiscount() + "\n");
System.out.printf("%-16s %-50.30s %.2f\t\t %.2f\t\t %.2f\n", adminObject.getProductCode(), adminObject.getName().substring(0, maxLength), adminObject.getPrice(), adminObject.getQuantity(), netAmount);
//System.out.println(adminObject.getProductCode() + "\t \t " + adminObject.getName() + "\t\t " + adminObject.getPrice() + "\t\t " + adminObject.getQuantity() + "\t\t " + adminObject.getTax() + "\t " + adminObject.getDiscount());
}
write1.write("___________________________________________________");
write1.write("\nGrand Total = PHP %.2f\n\n" + grandTotal);
write1.write("Money: " + money + "\n");
write1.write("Change: " + (change = money - grandTotal) + "\n");
write1.write("___________________________________________________\n");
System.out.println("___________________________________________________\n");
System.out.printf("\nGrand Total = PHP %.2f\n\n", grandTotal);
System.out.println("Money: " + money + "\n");
System.out.println("Change: " + (change = money - grandTotal) + "\n");
System.out.println("___________________________________________________\n");
}
} else {
System.out.println("___________________________________________________\n");
System.out.println("***Money exceeds the amount.***");
System.out.println("___________________________________________________\n");
}
pharmacyFile.close();
} catch (FileNotFoundException e) {
System.out.println("File Not Found" + e);
} catch (IOException e) {
System.out.println("File Not Found");
} catch (NumberFormatException e) {
System.out.println(e);
} catch (Exception e) {
System.out.println(e);
}
break;
You have to close the writer at the end via writer1.close(). Because you have a BufferedWriter, it is not writing to the file always immediately. If then your program for example exits before it can write, your content to the file, it will remain blank.
Also you should just in general always close this kind of resources at the end as they might cause memory leaks and other problems. You can do it via:
try (FileWriter writer1 = new FileWriter(new File("blablub")) {
// ... do your stuff with the writer
}
This is called a try-with-resources clause and will close the Resource in the end automatically. The more explicit version is:
FileWriter writer1 = new FileWriter(newFile("blablub"));
try {
// ... do your stuff with the writer
} catch (Exception ex) {
...
} finally {
writer1.close();
}
Edit: It might be, that you are thinking that you are closing the writer1 as I've now seen, but actually you have two calls to pharmacyFile.close(). Maybe this is your issue.

How do I display an error message if a file is not found?

I wrote a program to read from a specific file and was wondering how would I display a custom message if that file were to not be found. What I have currently does not work, could someone explain why?
try {
//create the file writer
Fwrite = new FileWriter(file);
Fwrite.write("Student Name \t\t\t Test Score \t Grade\n");
for (int i = 0; i < size; i++) {
Fwrite.write(students[i].getStudentLName() + ", " + students[i].getStudentFName() +
" \t\t\t "+ students[i].getTestScore() + " \t\t " + students[i].getGrade() + "\n");
}
Fwrite.write("\n\nHighest Test Score: " + highestScore + "\n");
Fwrite.write("Students having the highest test score\n");
//writes the test scores in descending order
for (int i = 0; i < size; i++) {
if (students[i].getTestScore() == highestScore) {
Fwrite.write(students[i].getStudentLName() + ", ");
Fwrite.write(students[i].getStudentFName() + "\n");
}
}
//catches any errors
} catch (IOException e) {
System.err.println("File mot Found!");
e.printStackTrace();
}
//try catch method to catch any errors
System.out.println("File Complete!");
//close file
Fwrite.close();
To show file not found exception change catch block to this
catch(FileNotFoundException e){
e.printStackTrace();
}
This exception will be thrown by the FileInputStream, FileOutputStream, and RandomAccessFile constructors when a file with the specified pathname does not exist. It will also be thrown by these constructors if the file does exist but for some reason is inaccessible, for example when an attempt is made to open a read-only file for writing.
CHECK THIS Link https://docs.oracle.com/javase/7/docs/api/java/io/FileNotFoundException.html

Java File Handling Editing records

I made a code for my system which would update a record in my text file database but I cant seem to make it work. The code doesnt have any error. its just not doing what I intend it to do
public static void Update() throws Exception {
File tempfile2 = new File("temp.txt");
tempfile2.createNewFile();
FileInputStream tempFStream = new FileInputStream(tempfile2);
BufferedReader read = new BufferedReader(new InputStreamReader(tempFStream));
System.out.print("Product Number: ");
String searchnum = br.readLine();
try {
LoadFile();
boolean found = false;
for (int i = 0; i < row; i++) {
String record[] = list.get(i).split(",");
if (!searchnum.equals(record[0])) {
found = true;
FileWriter fw = new FileWriter(tempfile2, true);
fw.write(record[0] + "," + record[1] + "," + record[2] + "," + record[3] + "," + record[4] + "," + record[5] + "\r\n");
fw.close();
}
}
for (int i = 0; i < row; i++) {
String record[] = list.get(i).split(",");
if (searchnum.equals(record[0])) {
found = true;
System.out.println("\t\t\t*******************************");
System.out.println("\t\t\t PIXBOX PHOTOBOOTH");
System.out.println("\t\t\t*******************************");
System.out.println("\n\t\t\tRecord Found:");
System.out.println("\n\t\t\tProduct Number : " + record[0]);
System.out.println("\t\t\tCategory : " + record[1]);
System.out.println("\t\t\tProduct Name : " + record[2]);
System.out.println("\t\t\tPrice [m/d/y] : " + record[3]);
System.out.println("\t\t\tQuantity : " + record[4]);
System.out.println("\n\n\t\t\t--------------------------------");
System.out.print("\t\t\tAre you sure you want to replace the records?<Y/N>: ");
String del = br.readLine();
if (del.equals("Y") || del.equals("y")) {
LoadFile();
System.out.println("\t\t\t*******************************");
System.out.println("\t\t\t PIXBOX PHOTOBOOTH");
System.out.println("\t\t\t*******************************");
System.out.println("\n\n\t\t\t------Update Record Form------");
System.out.print("\n\n\t\t\tProduct Number : ");
int prodnum = Integer.parseInt(br.readLine());
System.out.print("\t\t\tCategory : ");
String cat = br.readLine();
System.out.print("\t\t\tProduct Name :");
String prodname = br.readLine();
System.out.print("\t\t\tPrice: ");
String price = br.readLine();
System.out.print("\t\t\tQuantity : ");
String quan = br.readLine();
read.close();
database.delete();
boolean rename = false;
if (rename = tempfile2.renameTo(database)) {
InsertRecords(prodnum, cat, prodname, price, quan);
System.out.println("\t\t\tSuccessfully Edited!");
exiting();
} else {
System.out.print("Edit Failed!");
}
} else if (del.equals("N") || del.equals("n")) {
MainMenu();
}
}
if (!searchnum.equals(record[1])) {
System.out.println("\n\t\t\tNo Record Found.");
Thread.sleep(2000);
exiting();
}
}
} catch (Exception e) {
System.out.print("File Empty!");
}
}
public static void LoadFile()throws Exception
{
list.clear();
FileInputStream fis = new FileInputStream(database);
BufferedReader read = new BufferedReader(new InputStreamReader(fis));
row = 0;
while(read.ready())
{
list.add(read.readLine());
row++;
}
read.close();
}
Everytime I run this... it would work until Product Number: User input and after entering a number it would directly display File is empty which is at the end of the program. its as if the try/catch is ignored. I definitely did something wrong but I dont know what I did wrong. Anyone shed me some light? Thanks
and with the e.printStackTrace(); here's what displayed after entering a product number...
java.lang.ArrayIndexOutofBoundException:5
at SnackTimeInventorySystem.Update<SnackTimeInventorySystem.java:525>
at SnackTimeInventorySystem.MainMenu<SnackTimeInventorySystem.java:66>
at SnackTimeInventorySystem.Login<SnackTimeInventorySystem.java:369>
at SnackTimeInventorySystem.main<SnackTimeInventorySystem.java:14>
Turns out I only had 5 entries on my array but declared 6 entries to be written
System.out.println("\t\t\t*******************************");
System.out.println("\t\t\t PIXBOX PHOTOBOOTH");
System.out.println("\t\t\t*******************************");
System.out.println("\n\t\t\tRecord Found:");
System.out.println("\n\t\t\tProduct Number : " + record[0]);
System.out.println("\t\t\tCategory : " + record[1]);
System.out.println("\t\t\tProduct Name : " + record[2]);
System.out.println("\t\t\tPrice [m/d/y] : " + record[3]);
System.out.println("\t\t\tQuantity : " + record[4]);
System.out.println("\n\n\t\t\t--------------------------------");
fw.write(record[0] + "," + record[1] + "," + record[2] + "," + record[3] + "," + record[4] + "," + record[5] + "\r\n");
So I just had to delete record[5] and fixed the problem thanks to Tom

Java if statements and write lines

I am trying to get my if statements to have seperate write commands such as bw.write(b + " - " + a +" = " + c + newLine); the issue is due to the newLine string and the bw
Buffer being within curley braces I cannot get those to work. any ideas?
try {
File file = new File("src/written.txt");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file, true);
BufferedWriter bw = new BufferedWriter(fw);
String newLine = System.getProperty("line.separator");
bw.write(b + " - " + a +" = " + c + newLine);
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
JOptionPane.showMessageDialog(null,"Amount Transfered: " + b + " - " + "Previous Balance: " + a +"\nRemaning Balance: " + c);
if( c == 0){
JOptionPane.showMessageDialog(null,"Transfered granted. Balance empty","Transation successful!",JOptionPane.WARNING_MESSAGE);
}else if (c > 0){
JOptionPane.showMessageDialog(null,"Transfered granted.","Transation successful!",JOptionPane.INFORMATION_MESSAGE);
}else{
JOptionPane.showMessageDialog(null,"Transfer denied due to insufficent funds.","Transaction denied!",JOptionPane.ERROR_MESSAGE);
}
I'm not entirely sure what your goal is, but it looks like you're losing the scope on your BufferedWriter bw.
If you want to use bw outside the { } it currently resides in, declare:
BufferedWriter bw;
try {
.....
bw = new BufferedWriter(fw);
}
That way, bw is declared before the try block, which lets you use it all throughout the rest of the code as well as within the try block.

Is it possible to read a line from a file using StreamTokenizer?

I need to read a line from a file, and output it onto the console.
I have tried using the BufferedReader however this is messing up my StreamTokenizer.lineno(), so I was wondering whether I could tackle this from a different angle.
This is the snippet of my code which is outputting to another file
try {
PrintWriter out = new PrintWriter(new FileWriter("Parsed_Files" + timeStamp + ".csv"));
boolean eof = false;
int count = 0;
do {
int token = st.nextToken();
switch (token) {
case StreamTokenizer.TT_EOF:
System.out.println("End of File encountered.");
eof = true;
break;
default:
if (token == '\'' || token == '\"') {
if (st.sval.length() == 3) {
if (isNumeric(st.sval)) {
//output to the CSV File
System.out.println("Writing to File");
out.println("File Name: " + fileName);
out.println("Code Number: " + st.sval);
out.println("Line: " + br.readLine());
out.println("Line Number: " + st.lineno());
out.println("-----------------------------------"
+ "------------------------------------");
out.println("");
count++;
}
}
}
}
} while (!eof);
}

Categories

Resources