As a way to learn java, I attempted to write something simulating a bank(adding or removing numbers). I succeeded in creating a file(if one does not exist already), and then read from it, but when I attempt to write to it, it fails. I started with FileWriter, where it just erased the text in the document(balance.txt). I then tried BufferedWriter, and it wrote to the document, but it was just symbols instead of actual text/numbers. I'm aware that I'm a newbie when it comes to coding, but is there a solution to this? Thank you.
if (choice.equals("ADD")){
System.out.println("Currently selected: " + choice);
//write to file
try {
String filePath = "C:\\Users\\user\\Desktop\\programming\\projects\\java\\RandomStuff\\Bank\\balance.txt";
// System.out.println("How much would you like to add?");
// Scanner inputAdd = new Scanner(System.in);
// String balanceToAdd = inputAdd.nextLine();
// writeToFile.write(balanceToAdd);
int balanceToAdd = 1;
BufferedWriter out = new BufferedWriter(new FileWriter(filePath));
out.write(balanceToAdd);
out.close();
System.out.println("Added: " + balanceToAdd);
} //try end
catch(IOException e){
System.out.println("Error(line56): " + e.getMessage());
}
public FileWriter(String fileName,
boolean append)
I think you should use append to edit your file.
BufferedWriter out = new BufferedWriter(new FileWriter(filePath,true));
Related
This is my code, I am trying to write a text file replacing "Up" and "Right" with ↑ and →. The problem is that the text file output is: "→ ↑"(this is not what i wanted) and the console output is "↑ →".
private static void print(String t){
File log = new File("a.txt");
String raw = t;
raw = raw.replaceAll("Up", " \u2191 "); //↑
raw = raw.replaceAll("Right", " \u2192 "); //→
try{
FileWriter fileWriter = new FileWriter(log, true);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
bufferedWriter.write(raw + "\n");
System.out.println(raw + "\n")
bufferedWriter.close();
}catch(IOException e) {}
}
I think it may be an encoding error, but I dont know how to fix it.
First of all, it's best to specify the encoding (you probably want UTF-8) before you write your file.
private static void print(String t){
File log = new File("a.txt");
String raw = t;
raw = raw.replaceAll("Up", " \u2191 ");
raw = raw.replaceAll("Right", " \u2192 ");
try{
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(log), "UTF-8"));
bufferedWriter.write(raw + "\n");
System.out.println(raw + "\n");
bufferedWriter.close();
}catch(IOException e) {}
}
Then, you need to make sure that your file viewer is also set to UTF-8. It seems that your file viewer might be viewing the file in ANSI instead. Changing that setting would depend on your file viewer -- try Googling "[your file viewer name] UTF-8".
so I'm designing a text editor. For the Open/Save methods, I'm trying to use a TextArea (it doesn't have to be one, it's just my current method). Now, I have two problems right now:
1) When I load a file, it currently doesn't remove the contents currently in the text editor. For example, if I typed in "Owl", then loaded a file that contained "Rat", it would end up as "OwlRat". To solve this, I plan to use the replaceRange method (again however, it isn't absolute, any suggestions would be great!). However, I must replace all the contents of the text editor, not just selected text, and I can't figure out how to do that. Any tips?
2) Currently, when I load a file, nothing will happen unless I saved that file the same time I ran the application. So, for example, running the program, saving a file, closing the program, running the program again, and then loading the file will give nothing. I know this is because the String x doesn't carry over, but I can't think of anyway to fix it. Somebody suggested Vectors, but I don't see how they would help...
Here is the code for the Open/Save methods:
Open:
public void Open(String name){
File textFile = new File(name + ".txt.");
BufferedReader reader = null;
try
{
textArea.append(x);
reader = new BufferedReader( new FileReader( textFile));
reader.read();
}
catch ( IOException e)
{
}
finally
{
try
{
if (reader != null)
reader.close();
}
catch (IOException e)
{
}
}
}
Save:
public void Save(String name){
File textFile = new File(name + ".txt");
BufferedWriter writer = null;
try
{
writer = new BufferedWriter( new FileWriter(textFile));
writer.write(name);
x = textArea.getText();
}
catch ( IOException e)
{
}
finally
{
try
{
if ( writer != null)
writer.close( );
}
catch ( IOException e)
{
}
}
}
I had this same problem my guy friend, after much thought and research I even found a solution.
You can use the ArrayList to put all the contents of the TextArea and send as parameter by calling the save, as the writer just wrote string lines, then we use the "for" line by line to write our ArrayList in the end we will be content TextArea in txt file.
if something does not make sense, I'm sorry is google translator and I who do not speak English.
Watch the Windows Notepad, it does not always jump lines, and shows all in one line, use Wordpad ok.
private void SaveActionPerformed(java.awt.event.ActionEvent evt) {
String NameFile = Name.getText();
ArrayList< String > Text = new ArrayList< String >();
Text.add(TextArea.getText());
SaveFile(NameFile, Text);
}
public void SaveFile(String name, ArrayList< String> message) {
path = "C:\\Users\\Paulo Brito\\Desktop\\" + name + ".txt";
File file1 = new File(path);
try {
if (!file1.exists()) {
file1.createNewFile();
}
File[] files = file1.listFiles();
FileWriter fw = new FileWriter(file1, true);
BufferedWriter bw = new BufferedWriter(fw);
for (int i = 0; i < message.size(); i++) {
bw.write(message.get(i));
bw.newLine();
}
bw.close();
fw.close();
FileReader fr = new FileReader(file1);
BufferedReader br = new BufferedReader(fr);
fw = new FileWriter(file1, true);
bw = new BufferedWriter(fw);
while (br.ready()) {
String line = br.readLine();
System.out.println(line);
bw.write(line);
bw.newLine();
}
br.close();
fr.close();
} catch (IOException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(null, "Error in" + ex);
}
There's a lot going on here...
What is 'x' (hint: it's not anything from the file!), and why are you appending it to the text area?
BufferedReader.read() returns one character, which is probably not what you're expecting. Try looping across readline().
Follow Dave Newton's advice to handle your exceptions and provide better names for your variables.
The text file will persist across multiple invocation of your program, so the lack of data has nothing to do with that.
Good luck.
Use textArea.setText(TEXT); rather than append; append means to add on to, so when you append text to a TextArea, you add that text to it. setText on the other hand will set the text, replacing the old text with the new one (which is what you want).
As far as why it's failing to read, you are not reading correctly. First of all, .read() just reads a single character (not what you want). Second, you don't appear to do anything with the returned results. Go somewhere (like here) to find out how to read the file properly, then take the returned string and do textArea.setText(readString);.
And like the others said, use e.printStackTrace(); in all of your catch blocks to make the error actually show up in your console.
i have a file DataFile.txt with few records. when i am adding new entry, it clears all the other records and saving only new one. but i want to append that record.
private void saveFile()
{
try
{
PrintWriter out = new PrintWriter(new FileWriter("DataFile.txt"));
String name ="";
String ID="";
String roomType ="";
String meal="";
int days=0;
int tprice=0;
for (int i = 0; i < myList.size(); i++)
{
Customer c = myList.get(i);
name = c.getName();
ID = c.getID();
roomType = c.getRoomItem();
meal = c.getMealItem();
days = c.getDaysIndex();
tprice = c.getTotalPrice();
out.println(name + "," + ID+ "," + roomType+ "," + meal+ "," + days+ "," + tprice);
}
out.close();
JOptionPane.showMessageDialog(null,"Data saved successfully!","",
JOptionPane.INFORMATION_MESSAGE);
}
catch (Exception ex)
{
System.out.println("save file fail");
}
} //end of the method
thanks.
You can change to use the FileWriter constructor which takes a boolean append parameter:
PrintWriter out = new PrintWriter(new FileWriter("DataFile.txt", true));
However:
PrintWriter swallows exceptions - I wouldn't use it if I were you
FileWriter always uses the platform default encoding - I wouldn't use that, either. I'd use an OutputStream wrapped in an OutputStreamWriter created with a specific encoding.
Do not use FileWriter. It is not possible to define character encoding with FileWriter aand you will end up using system default encoding, which usually will not be what you want to use.
Instead use FileOutputStream and an OutputStreamWriter. Yes, it is an extra line of code, but that extra line is required if you want to write robust and bug free code.
OutputStream out = new FileOutputStream("output.txt", true);
Writer writer = new OutputStreamWriter(out, "UTF-8");
Using system default character encoding is the most common source for bugs. Make a habit of learning to not rely on system default character encoding (or system default time zone).
I am new to Java and trying to save a multi line string to a text file.
Right now, it does work within my application. Like, if I save the file from my application and then open it from my application, it does put a space between lines. However, if I save the file from my app and then open it in Notepad, it is all on one line.
Is there a way to make it show multi line on all programs? Here's my current code:
public static void saveFile(String contents) {
// Get where the person wants to save the file
JFileChooser fc = new JFileChooser();
int rval = fc.showSaveDialog(fc);
if(rval == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
try {
//File out_file = new File(file);
BufferedWriter out = new BufferedWriter(new FileWriter(file));
out.write(contents);
out.flush();
out.close();
} catch(IOException e) {
messageUtilities.errorMessage("There was an error saving your file. IOException was thrown.", "File Error");
}
}
else {
// Do nothing
System.out.println("The user choose not to save anything");
}
}
depending on how you are constructing your string, you may just be running into a line ending problem. Notepad does not support unix line endings (\n only) it only supports windows line endings (\n\r). try opening your saved file using a more robust editor, and/or make sure you are using the proper line endings for your platform. java's system property (System.getProperty("line.separator")) will get you the proper line ending for the platform that the code is running on.
while you're building your string to be saved to the file, rather than explicitly specifying "\n" or "\n\r" (or on the mac "\r") for your line endings, you would instead append the value of that system property.
like so:
String eol = System.getProperty("line.separator");
... somewhere else in your code ...
String texttosave = "Here is a line of text." + eol;
... more code.. optionally adding lines of text .....
// call your save file method
saveFile(texttosave);
Yea as the previous answer mentions the System.getProperty("line.seperator").
your code doesn't show how you created String contents but since you said you were new to java I thought i'd mention that in java concatenating Strings is not nice since it creates a. If you are building the String by doing this:
String contents = ""
contents = contents + "sometext" + "some more text\n"
Then consider using java.lang.StrinBuilder instead
StringBuilder strBuilder = new StringBuilder();
strBuilder.append("sometext").append("somre more text\n");
...
String contents = strBuilder.toString();
Another alternative is to stream what ever your planning to write to a file rather than building a large string and then outputting that.
You could add something like:
contents = contents.replaceAll("\\n","\\n\\r");
if notepad does not display correctly. However you might run into a different problem: at each save/load you will get multiple \r chars. Then to avoid that at load you would have to call the same code above but with reversed parameters. This is really an ugly solution just to get the text to display properly in notepad.
I had this same problem my guy friend, after much thought and research I even found a solution.
You can use the ArrayList to put all the contents of the TextArea for exemple, and send as parameter by calling the save, as the writer just wrote string lines, then we use the "for" line by line to write our ArrayList in the end we will be content TextArea in txt file.
if something does not make sense, I'm sorry is google translator and I who do not speak English.
Watch the Windows Notepad, it does not always jump lines, and shows all in one line, use Wordpad ok.
private void SaveActionPerformed(java.awt.event.ActionEvent evt) {
String NameFile = Name.getText();
ArrayList< String > Text = new ArrayList< String >();
Text.add(TextArea.getText());
SaveFile(NameFile, Text);
}
public void SaveFile(String name, ArrayList< String> message) {
path = "C:\\Users\\Paulo Brito\\Desktop\\" + name + ".txt";
File file1 = new File(path);
try {
if (!file1.exists()) {
file1.createNewFile();
}
File[] files = file1.listFiles();
FileWriter fw = new FileWriter(file1, true);
BufferedWriter bw = new BufferedWriter(fw);
for (int i = 0; i < message.size(); i++) {
bw.write(message.get(i));
bw.newLine();
}
bw.close();
fw.close();
FileReader fr = new FileReader(file1);
BufferedReader br = new BufferedReader(fr);
fw = new FileWriter(file1, true);
bw = new BufferedWriter(fw);
while (br.ready()) {
String line = br.readLine();
System.out.println(line);
bw.write(line);
bw.newLine();
}
br.close();
fr.close();
} catch (IOException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(null, "Error in" + ex);
}
I'm working on an assignment for school, and am trying something beyond for extra credit. The program is to demonstrate the efficiency differences between a linear & binary search for a given array size of integers. I have a loop set up that creates an int[size] array, searches for a random number, then creates a new array of int[size*2].
The results are then written to a text file. The output writes fine, but after compiling & running the program several times, the output file has that many sections of data.
This is my code that is nested inside a try/catch block:
File output= new File("c:\\BigOhResults.txt");
int counter=2;
if (output.canWrite() && output.exists()) {
BufferedWriter out= new BufferedWriter(new FileWriter(output, true));
out.write(type+" \n\n"); //writes the search type
out.write(type+"Search Results\n\n");
while (counter <= data.size()) {
out.write(data.get(counter-1)+" millisecond runtime " +
"for a "+ data.get(counter-2)+" random number " +"sample size\n");
counter=counter+2;
}
}
Is there any way I can erase the text within that output file upon each time the program is run?
the reason I'm doing this is the professor requires the result printout with the data graphed. I have already completed the graphing requirement, and it works fine. I just want to have the file printout match the graph printout.
The second argument to the FileWriter constructor, which you're passing in "true", is "append". I.e. because you've set it to true, it will append your new output to the end of the file. If you pass in false instead, it will wipe the data that's there already and write it new.
Read the documentation for FileWriter. You do not want to append.
As already mentioned, the [FileWriter][1] constructor allows you to specify to clear the existing text and start at the beginning of the file. Some other remarks about the code:
The check on output.exists() is redundant after a call to output.canWrite() and isn't needed. output.canWrite() will check if the file exists and that you can write to it.
Don't forget to close the BufferedWriter object.
Like so:
if (output.canWrite()) {
BufferedWriter out = null;
try {
out = new BufferedWriter(new FileWriter(output, false));
out.write(type+" \n\n"); //writes the search type
out.write(type+"Search Results\n\n");
while (counter <= data.size()) {
out.write(data.get(counter-1)+" millisecond runtime " +
"for a "+ data.get(counter-2)+" random number " +"sample size\n");
counter=counter+2;
}
} catch (IOException e) {
// Do what you want here, print a message or something
} finally {
if(out != null) {
try {
out.close();
} catch (IOException e) {
// Again, do what you want here
}
}
}
}
[1]: http://java.sun.com/j2se/1.4.2/docs/api/java/io/FileWriter.html#FileWriter(java.io.File, boolean)
Okay so I tried something and it worked. This is when you have a file that is intended to append any new text, but you want to reset/erase the contents of the file at the beginning of program execution. Hope I made sense.
PrintWriter pw1 = new PrintWriter(new BufferedWriter(new FileWriter("newfile.txt")));
pw1.close(); // Make sure the first PrintWriter object name is different from the second one.
PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter("newfile.txt", true))); // PrintWriter in append-mode. When you recreate the text file with the same name, the file contents are erased because the previous object was not in append mode.
pw.close();