appendFile into textfile that dont overwrite - java

Im loosing on append method.
I have a program that inputs an information then printing in a text file.
The problem is, I want to append the new input of information into text file too without overwriting, it means that if I rerun the program the information that I encoded will be in the textfile together with the encoded on the last run of the program.
Please help me. Here is the program:
#SuppressWarnings("resource")
public static void main(String[] args) throws IOException
{
System.out.println("STUDENT INFORMATION");
System.out.println("-------------------");
System.out.println("Full Name : ");
Scanner sc = new Scanner(System.in);
String name = sc.nextLine();
System.out.println("\nCourse and Year : ");
String yearcourse = sc.nextLine();
System.out.println("\nStudent Number : ");
String studentnumber = sc.nextLine();
System.out.println("\nE-mail Address : ");
String eadd = sc.nextLine();
System.out.println("\nCellphone Number : ");
String cpnumber = sc.nextLine();
System.out.println("\nGender : ");
String gender = sc.nextLine();
System.out.println("\nAge : ");
String age = sc.nextLine();
System.out.println("\nDate of Birth : ");
String dob = sc.nextLine();
System.out.println("\nCivil Status : ");
String status = sc.nextLine();
System.out.println("\nAddress : ");
String address = sc.nextLine();
System.out.println("\n\n________________________________________________");
System.out.println("STUDENT INFORMATION");
System.out.println("\nName : " + name + "");
System.out.println("Year and Course : " + yearcourse + "");
System.out.println("Student Number : " + studentnumber + "");
System.out.println("E-mail Address : " + eadd + "");
System.out.println("Cellphone Number : " + cpnumber + "");
System.out.println("Gender : " + gender + "");
System.out.println("Age : " + age + "");
System.out.println("Date of Birth : " + dob + "");
System.out.println("Civil Status : " + status + "");
System.out.println("Address : " + address + "");
System.out.println("");
File file = new File("Student Information.txt");
if(!file.exists())
{
file.createNewFile();
}
try (PrintWriter writer = new PrintWriter(file)){
BufferedWriter bufferWritter = new BufferedWriter(writer);
writer.println("\nSTUDENT INFORMATION:");
writer.println("--------------------");
writer.println("Name : " + name + "");
writer.println("Year and Course : " + yearcourse + "");
writer.println("Student Number : " + studentnumber + "");
writer.println("E-mail Address : " + eadd + "");
writer.println("Cellphone Number : " + cpnumber + "");
writer.println("Gender : " + gender + "");
writer.println("Age : " + age + "");
writer.println("Date of Birth : " + dob + "");
writer.println("Civil Status : " + status + "");
writer.println("Address : " + address + "");
writer.flush();
}
}
}
In this. if I rerun the program, the text file will just overwrite with the new encoded information. They said to use append bufferwriter. but I'm really lost.

Try to change your code to something like this:
File file = new File("Student Information.txt");
if(!file.exists())
{
file.createNewFile();
}
try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file, true)))) {
out.println("\nSTUDENT INFORMATION:");
out.println("--------------------");
out.println("Name : " + name + "");
out.println("Year and Course : " + yearcourse + "");
out.println("Student Number : " + studentnumber + "");
out.println("E-mail Address : " + eadd + "");
out.println("Cellphone Number : " + cpnumber + "");
out.println("Gender : " + gender + "");
out.println("Age : " + age + "");
out.println("Date of Birth : " + dob + "");
out.println("Civil Status : " + status + "");
out.println("Address : " + address + "");
}catch (IOException e) {
// Handle IO exception.
}
This part of the code:
new FileWriter(file,true)
tells it to append when it's set to true, as you can see on the docs.
Or you could change your line:
PrintWriter writer = new PrintWriter(file);
To this:
PrintWriter writer = new PrintWriter(new FileWriter(file,true));

instead of this
PrintWriter writer = new PrintWriter(file);
try this
PrintWriter writer= new PrintWriter(new BufferedWriter(new FileWriter(file, true));
See Also
How to append content to file in Java
How to append text to an existing file in Java

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.

Read File and extract to different output

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);
}
}
}

Printstream input to a text file

// I'm searching for an Int in a text file, displaying that Int on console, creating a text file to print that Int. I get this instead of an Int:
java.util.Scanner[delimiters=\p{javaWhitespace}+][position=666][match valid=true][need input=false][source closed=false][skipped=false][group separator=\,][decimal separator=\.][positive prefix=][negative prefix=\Q-\E][positive suffix=][negative suffix=][NaN string=\Q�\E][infinity string=\Q∞\E]1920: ,
public static void findName(Scanner input, String name) throws FileNotFoundException {
boolean find = false;
while (find == false && input.hasNext()) {
String search = input.next();
if (search.startsWith(name) && search.endsWith(name)) {
PrintStream output = new PrintStream(new File(name + ".txt"));
output.println(name + ",");
System.out.println("1920: " + input.nextInt());
output.println("1920: " + input + ","); // need help here. HOW DO I GET THIS TO PRINT THE SAME INT, NOT GO TO THE SECOND INT?
System.out.println("1930: " + input.nextInt());
output.println("1930: " + input + ",");
System.out.println("1940: " + input.nextInt());
output.println("1940: " + input + ",");
System.out.println("1950: " + input.nextInt());
output.println("1950: " + input + ",");
System.out.println("1960: " + input.nextInt());
output.println("1960: " + input + ",");
System.out.println("1970: " + input.nextInt());
output.println("1970: " + input + ",");
System.out.println("1980: " + input.nextInt());
output.println("1980: " + input + ",");
System.out.println("1990: " + input.nextInt());
output.println("1990: " + input + ",");
System.out.println("2000: " + input.nextInt());
output.println("2000: " + input);
find = true;
}
}
if (find == false) {
System.out.println("name not found.");
you're printing the input object instead of the int into the file.
try this:
int next = input.nextInt()
System.out.println("1920: " + next );
output.println("1920: " + next + ",");
...
Hope this helps

Output on new line WITHOUT for loop

I am trying to output arrays on a new line through a basic client, server application. However, to accomplish this I have had to use substring to find the # after each word to signal the end of the line. However I want to remove this function and have each section on a new line.
public ClientHandler(Socket socket,Users newUser, int newClientUser)
throws IOException
{
client = socket;
input = new Scanner(client.getInputStream());
output = new PrintWriter(
client.getOutputStream(),true);
user = newUser;
clientUser = newClientUser;
String[] itemName = {user.getItemName(1), user.getItemName(2)};
String[] description = {user.getItemDescription(1), user.getItemDescription(2)};
String[] itemtime = {user.getItemTime(1), user.getItemTime(2)};
output.println(itemName[0] + "#" + itemName[1]
+ "#" + "Welcome To The Auction User:" + clientUser
+ itemName[0] +": "+ description[0] +
"#"+ itemName[1] +": "+description[1]+
"#"+ "Deadline For " + itemName[0] + ": "
+ itemtime[0] + "#" +"Deadline For " +
itemName[1] + ": " + itemtime[1]+"#");
}
private synchronized void getMessage(String response)
{
String message="";
for(int i= count; !response.substring(i, i+1).equals("#"); i++)
{
count = i;
}
}
output.println(itemName[0] + "\n" + itemName[1]
+ "\n" + "Welcome To The Auction User:" + clientUser
+ itemName[0] +": "+ description[0] +
"\n"+ itemName[1] +": "+description[1]+
"\n"+ "Deadline For " + itemName[0] + ": "
+ itemtime[0] + "\n" +"Deadline For " +
itemName[1] + ": " + itemtime[1]+"\n");
Instead of having a "#" signify a new line, you can use "\n". Java will read that from your string as a new line.

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

Categories

Resources