I'm making a savings calculator using netbeans with a JFrameForm. below is my working code to save to a .txt. for some reason when I click save it will not append to a new line and wont save at all. I would like to then load certain rows to an array and display in my text area. eg the savings field. First code for the save button, second block for the load button.
BufferedWriter writer = null;
try{
writer = new BufferedWriter(new FileWriter("C:\\test.txt"));
writer.write("\n" + date + "\t" + gross + "\t" + tax + "\t" + savings);
}
catch (Exception e){
JOptionPane.showMessageDialog(null, "Error saving");
}finally{
try{
//close the writer
writer.close();
}catch (Exception e){
JOptionPane.showMessageDialog(null, "Error closing save");
}
}
try{
FileReader reader = new FileReader("C:\\test.txt");
BufferedReader br = new BufferedReader(reader);
txaMain.read(br, null);
br.close();
}
catch(Exception E){
JOptionPane.showMessageDialog(null, "Error opening file");
}
for some reason when I click save it will not append to a new line and wont save at all
It is not saving because you are not flushing the character buffer stream that was grab from your write method.
solution:
flush it after you write from the text file
writer = new BufferedWriter(new FileWriter("C:\\test.txt"));
writer.write("\n" + date + "\t" + gross + "\t" + tax + "\t" + savings);
writer.flush();
Also if you want to append to the file while saving the text then add one more parameter in your FileWriter FileWriter("C:\\test.txt, true") true means to append the file when writing.
public FileWriter(String fileName,
boolean append)
Related
I am writing to an internal file in Android Studio
String filename = "output.txt";
String fileContents = studentNum + ", " + lastName + ", " + firstName + ", " + radioValue + ", " + spinnerInfo + "\n"; // edit this to include all content
FileOutputStream outputStream;
try{
outputStream = openFileOutput(filename, Context.MODE_APPEND);
outputStream.write(fileContents.getBytes());
outputStream.close();
} catch(Exception e){
e.printStackTrace();
}
}
The code lets me write lines of data split with commas. I am able to then go to another activity and read it all out at once.
String file = "output.txt";
String line = "";
String data = "";
//File read operation
try {
FileInputStream fis = openFileInput(file); //A FileInputStream obtains input bytes from a file in a file system
InputStreamReader isr = new InputStreamReader(fis); //An InputStreamReader is a bridge from byte streams to character streams
BufferedReader br = new BufferedReader(isr); //Reads text from a character-input stream,
while ((line = br.readLine()) != null) {
data += (counter+1) + "\t"+ line +"\n";
counter++;
}
}catch (FileNotFoundException e){
e.printStackTrace();
}
catch (IOException e){
e.printStackTrace();
}
//Show the data
txtOutput.setText(data);
However I want to be able to read only one line of data per activity and when I click a button it transfers down to the next line of data. And goes in a carousel loop so once we reach the last line it will go to the first line of data once the button is clicked again
The easiest thing is probably just to keep a line number pointer (since you are reading by line), and read down that many lines to get where you want at each activity. If the file is large or you are otherwise performance conscious this is not a great option.
Both InputStream and Reader have a skip(<bytes>) method. You could also do it that way. Obviously if you use a stream you need to read by bytes not by line, so a little more trouble.
You could also use a RandomAccessFile that has a seek() method. Again this is accessed by byte index.
Hello I am building a program that writes an output to a text file.
In my program my String looks like this:
MyName
Addres
Location
Paycheck
But when I write it to a text file it looks like this:
MyName Addres Location Paycheck
I am writing everything from a single toString method. How can I use bufferedwriter so that it formats the string while writing it?
Here's my code:
if (file != null) {
FileWriter fileWriter = null;
try {
fileWriter = new FileWriter(file.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
BufferedWriter out = new BufferedWriter(fileWriter);
try {
out.write(emp.toString());
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
EDIT:
Here is the toString method for the emp class:
#Override
public String toString() {
return "Name: " + name + " \nDOB: " + dob + " \nAddress: " + address + " \n******Paycheck******\nSalary: "
+ myPaycheck.getSalary() + "\nFederal Income: " + myPaycheck.getTaxes() + "\nSocial Security: "+ myPaycheck.getSocialSecurity() + "\nMedicare: " + myPaycheck.getMedicare()
+ "\nNet Salary: " + myPaycheck.getNetPay() + "";
}
bufferedwriter API
You can use "newLine" easily .
bw.newLine();
You either need to use System.lineSeparator() while writing text to file or change your toString() method to add a line separator between each line or object added
Edit
Your code writes your string as separate line only. Try reading the lines from output file and print each line, you will see that the reader treats each detail as separate line. Now if you wish to write it into the file with exact format so that it is shown in next line in file u have to give the inputs separately maybe by adding the objects to an ArrayList and iterating the same.
I have a BufferedWriter which is being used to write to a file the users details. I have noticed, however, it is not writing to file in the format I want it to, I can't seem to find a method which allows me to write text on a new line without it writing over what is already there or copy out the text already in the file. Is there any way I can edit the following code, to allow it to the above?
Details = "Name: " + name + " CardNo: " + CardNo + " Current Balance: " + balance + " overdraft? " + OverDraft + " OverDraftLimit: " + OverDraftLimit + " pin: " + PinToWrite;
try{
//Create writer to write to files.
File file = new File(DirToWriteFile);
FileOutputStream fos = new FileOutputStream(file, true);
Writer bw = new BufferedWriter(new OutputStreamWriter(fos, "UTF8"));
// FileReader reads text files in the default encoding.
FileReader fileReader = new FileReader("VirtualATM.txt");
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader = new BufferedReader(fileReader);
String currentData = "";
while((currentData=bufferedReader.readLine()) != null) {
line = currentData;
bw.write(currentData);
((BufferedWriter) bw).newLine();
}
bw.write(Details);
System.out.println("Account created!");
There is no problem with the program (all variables work properly and have been declared somewhere) I have only posted a snippet of the code which is relevant to the question. The current output to the file after running it a few times looks like this
I've got it! Change:
while((currentData=bufferedReader.readLine()) != null) {
line = currentData;
bw.write(currentData);
((BufferedWriter) bw).newLine();
}
bw.write(Details);
to:
bw.append(Details);
((BufferedWriter) bw).newLine();
This ensures that no data will be written twice and it will not copy out any text besides the information gained from the user.
I am not sure as to why the following code causes Java to override the data already in my file every time, when what I want it to do is actually write each new piece of data on a new line. I have included the relevant pieces of code (I understand you might be thinking that there are errors in the variables, but there isn't, the program works fine). Can someone help me understand as to what is causing this, is is the way I am using the file writer?
String DirToWriteFile = System.getProperty("user.dir") + "/VirtualATM.txt"; //Get path to write text file to.
String Details = "Name: " + name + " CardNo: " + CardNo + " Current Balance: " + balance + " overdraft? " + OverDraft + " OverDraftLimit: " + OverDraftLimit + " pin: " + PinToWrite;
try{
//Create writer to write to files.
File file = new File(DirToWriteFile);
Writer bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF8"));
// FileReader reads text files in the default encoding.
FileReader fileReader = new FileReader("VirtualATM.txt");
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader = new BufferedReader(fileReader);
String CurrentData = "";
while((bufferedReader.readLine()) != null) {
line = CurrentData;
bw.write(CurrentData);
((BufferedWriter) bw).newLine();
}
bw.write(Details);
System.out.println("Account created!");
System.out.println(name + " Your card number is: " + CardNo);
// close the reader.
bufferedReader.close();
//Close the writer.
bw.close();
Use the other FileOutputStream constructor, the one that takes a boolean append parameter as the second parameter. Pass in true as this will tell Java to append text to the existing File rather than over-write it.
i.e., change this:
File file = new File(DirToWriteFile);
Writer bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF8"));
to this:
File file = new File(DirToWriteFile);
FileOutputStream fos = new FileOutputStream(file, true); // **note second param?**
Writer bw = new BufferedWriter(new OutputStreamWriter(fos, "UTF8"));
This question already has answers here:
BufferedWriter not writing everything to its output file
(8 answers)
Closed 8 years ago.
I am doing a lab where we have to read in an external file, take some statistics on the data, and then create and write a new file with the stats. Everything in my program works except for writing the file, which I cannot understand why my method won't work.
BufferedWriter writer;
public void writeStats(int word, int numSent, int shortest, int longest, int average)
{
try
{
File file = new File("jefferson_stats.txt");
file.createNewFile();
writer = new BufferedWriter(new FileWriter(file));
writer.write("Number of words: " + word );
writer.newLine();
writer.write("Number of sentences: " + numSent );
writer.newLine();
writer.write("Shortest sentence: " + shortest + " words");
writer.newLine();
writer.write("Longest sentence: " + longest + " words");
writer.newLine();
writer.write("Average sentence: " + average + " words");
}
catch(FileNotFoundException e)
{
System.out.println("File Not Found");
System.exit( 1 );
}
catch(IOException e)
{
System.out.println("something messed up");
System.exit( 1 );
}
}
You have to flush and close your writer:
writer.flush();
writer.close();
You should always close opend resources explicitly or implicitly with Java 7 try-with-resources
try (BufferedWriter bw = new BufferedWriter(new FileWriter(file))) {
...
}
besides, there is a more convenient class to write text - java.io.PrintWriter
try (PrintWriter pw = new PrintWriter(file)) {
pw.println("Number of words: " + word);
...
}
You have to close your BufferedWriter using close():
writer.close();