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.
Related
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.
I have the following data. What I'm trying to do is to separate every reading into different outputs, but it does not work. It only show 'null'. What i expected to work are:
Output:
C.txt
1 1000 1000
2 2000 2000
Output: B.txt
1 2 90.000 2
2 3 180.000 2
Output: D.txt
1 2 100.1 0.038
2 3 200.1 0.038
Data in Input.txt:
C;1;1000;1000
C;2;2000;2000
B;1;2;90.00;2
B;2;3;180.00;2
D;1;2;100.1;0.038
D;2;3;200.1;0.038
import java.io.*;
import java.util.StringTokenizer;
public class ReadFile {
public static void main(String[] args) {
BufferedReader input = null; //read
PrintWriter outC = null; //write output
PrintWriter outB = null;
PrintWriter outD = null;
try {
input = new BufferedReader(new FileReader("C:\\Users\\PC\\Desktop\\FYP\\Input.txt"));
outC = new PrintWriter(new BufferedWriter(new FileWriter("C:\\Users\\PC\\Desktop\\FYP_Test\\C.txt")));
outB = new PrintWriter(new BufferedWriter(new FileWriter("C:\\Users\\PC\\Desktop\\FYP_Test\\B.txt")));
outD = new PrintWriter(new BufferedWriter(new FileWriter("C:\\Users\\PC\\Desktop\\FYP_Test\\D.txt")));
String inputData = null;
int C = 0;
int B = 0;
int D = 0;
while ((inputData = input.readLine()) != null) {
StringTokenizer tokenizer = new StringTokenizer(inputData, ";");
String id = tokenizer.nextToken();
String StnFrom = tokenizer.nextToken();
String NorthingTo = tokenizer.nextToken();
String EastingDistBrg = tokenizer.nextToken();
String StdError = tokenizer.nextToken();
if (id.equalsIgnoreCase("C")) {
C++;
outC.println(StnFrom + " " + NorthingTo + " " + EastingDistBrg);
} else if (id.equalsIgnoreCase("B")) {
B++;
outB.println(StnFrom + " " + NorthingTo + " " + EastingDistBrg + " " + StdError);
} else if (id.equalsIgnoreCase("D")) {
D++;
outB.println(StnFrom + " " + NorthingTo + " " + EastingDistBrg + " " + StdError);
}
}
input.close();
outC.close();
outB.close();
outD.close();
} catch (FileNotFoundException fe) {
System.out.println(fe.getMessage());
} catch (IOException iox) {
System.out.println(iox.getMessage());
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
tokenizer.nextToken() will throw NoSuchElementException when there are no more tokens in the tokenizer's string.
Your sample input, if provided, will throw "NoSuchElementException" because Data in "Input.txt" for "C" is wrong. In your program, you are calling "nextToken" five times, whereas data for "C" contains only 4 values(C;1;1000;1000).
Below, is improved "Input" data.
C;1;1000;1000;1
C;2;2000;2000;1
B;1;2;90.00;2
B;2;3;180.00;2
D;1;2;100.1;0.038
D;2;3;200.1;0.038
Also, you need to improve your while loop to read empty line. Currently, it will throw Error.
Consider below while loop:
while ((inputData = input.readLine()) != null) {
if(inputData.length() != 0) {
StringTokenizer tokenizer = new StringTokenizer(inputData, ";");
String id = tokenizer.nextToken();
String StnFrom = tokenizer.nextToken();
String NorthingTo = tokenizer.nextToken();
String EastingDistBrg = tokenizer.nextToken();
String StdError = tokenizer.nextToken();
if (id.equalsIgnoreCase("C")) {
C++;
outC.println(StnFrom + " " + NorthingTo + " " + EastingDistBrg);
} else if (id.equalsIgnoreCase("B")) {
B++;
outB.println(StnFrom + " " + NorthingTo + " " + EastingDistBrg + " " + StdError);
} else if (id.equalsIgnoreCase("D")) {
D++;
outD.println(StnFrom + " " + NorthingTo + " " + EastingDistBrg + " " + StdError);
}
}
}
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!");
}
}
I'm doing example from the book
"Java The Complete Reference Ninth Edition"
that demonstrates FileInputStream using try-with resources.
In the output I've got "I/O Error: java.io.FileNotFoundException: C:\Users\user\Documents\NetBeansProjects\JavaExam\FileInputStreamDemo.java (Can't find file)".
The code:
package javaexam;
import java.io.*;
class FileInputStreamDemo {
public static void main(String args[]) {
int size;
// Use try-with-resources to close the stream.
try ( FileInputStream f =
new FileInputStream("C:\\Users\\user\\Documents\\NetBeansProjects\\JavaExam\\FileInputStreamDemo.java"))
{
System.out.println("Total Available Bytes: " + (size = f.available()));
int n = size/40;
System.out.println("First " + n + " bytes of the file one read() at a time");
for (int i = 0; i < n; i++) {
System.out.print((char) f.read());
}
System.out.println("\nStill Available: " + f.available());
System.out.println("Reading the next " + n + " with one read(b[])");
byte b[] = new byte[n];
if (f.read(b) != n) {
System.err.println("couldn't read " + n + " bytes.");
}
System.out.println(new String(b, 0, n));
System.out.println("\nStill Available: " + (size = f.available()));
System.out.println("Skipping half of remaining bytes with skip()");
f.skip(size/2);
System.out.println("Reading " + n/2 + " into the end of array");
if (f.read(b, n/2, n/2) != n/2) {
System.err.println("couldn't read " + n/2 + " bytes.");
}
System.out.println(new String(b, 0, b.length));
System.out.println("\nStill Available: " + f.available());
} catch (IOException e) {
System.out.println("I/O Error: " + e);
}
}
}
I think your issue might be that you're using backslashes. I'm not certain, though. Try using a BufferedReader instead.
File file = new File("C:/Users/user/Documents/NetBeansProjects/JavaExam/FileInputStreamDemo.java");
BufferedReader bufferedreader = new BufferedReader(new FileReader(file));
Using this you should be able to read it a lot more easily, and line by line instead of byte by byte.
The file you are looking should be in the src folder under package javaexam. Otherwise it won't be compiled. By the Java conventions each public class should have the name of the file and reside in the folder with the name of the package.
new FileInputStream("C:\\Users\\user\\Documents\\NetBeansProjects\\JavaExam\\src\\javaexam\\FileInputStreamDemo.java"))
Like the title says, I can get it to write the first thing to the file I want it to, but after that it doesn't write any more. I run it through the debugger, and see that it's not even reading the next line (I know this because it's not filling the array.) I tried manually advancing the pointer (I don't know if that's actually a thing you can do) at the end of the loop with "line = in.readline;", but It just throws a "nosuchelement" exception. Here's my try block"
try
{
in = new BufferedReader(new FileReader("lab7input.txt"));
outNormal = new PrintWriter(new File("normal.txt"));
outVegetarian = new PrintWriter(new File("vegetarian.txt"));
outPescetarian = new PrintWriter(new File("pescetarian.txt"));
outInvalid = new PrintWriter(new File("invalid.txt"));
String line = in.readLine();
StringTokenizer st = new StringTokenizer(line);
while (line != null)
{
Scanner sc = new Scanner(line);
while(sc.hasNext())
{
if(st.countTokens() == 3)
{
attendee3[0] = sc.next();
attendee3[1] = sc.next();
attendee3[2] = sc.next();
if(Integer.parseInt(attendee3[2]) == 0)
{
outNormal.println(attendee3[0] + " " + attendee3[1]);
outNormal.close();
}
else if(Integer.parseInt(attendee3[2]) == 1)
{
outVegetarian.println(attendee3[0] + " " + attendee3[1]);
outVegetarian.close();
}
else if(Integer.parseInt(attendee3[2]) == 2)
{
outPescetarian.println(attendee3[0] + " " + attendee3[1]);
outPescetarian.close();
}
else
{
outInvalid.println(attendee3[0] + " " + attendee3[1]);
outInvalid.close();
}
}
if(st.countTokens() == 4)
{
attendee4[0] = sc.next();
attendee4[1] = sc.next();
attendee4[2] = sc.next();
if(Integer.parseInt(attendee4[3]) == 0)
{
outNormal.println(attendee4[0] + " " + attendee4[1] + " " + attendee4[2]);
outNormal.close();
}
else if(Integer.parseInt(attendee4[3]) == 1)
{
outVegetarian.println(attendee4[0] + " " + attendee4[1] + " " + attendee4[2]);
outVegetarian.close();
}
else if(Integer.parseInt(attendee4[3]) == 2)
{
outPescetarian.println(attendee4[0] + " " + attendee4[1] + " " + attendee4[2]);
outPescetarian.close();
}
else
{
outInvalid.println(attendee4[0] + " " + attendee4[1] + " " + attendee4[2]);
outInvalid.close();
}
}
//line = in.readLine();
}
}
}
a simpler and cleaner way would be
String line = in.readLine();
while (line != null)
{
String arr [] = line.split ();
if(arr.length == 3)
{
attendee3[0] = arr[0];
attendee3[1] = arr[1];
attendee3[2] = arr[2];
}
// other count code
line = in.readLine();
}
You have to put line = in.readLine() one block below and not in a while block of a scanner.
Not only that, i've had the experience that Scanner can only read in UTF-8 codeded .txt files. so always make sure that they are UTF-8 coded.
If they are not just simply open the file and save it with that coding.