I am developing an app, in which the user puts some numeric info in some text fields, the app is supposed to write the info into a txt file for later use, for example next time the app is opened or a refresh button is pressed the numbers should be read from the file and loaded into the same text fields so the user can change them if needed. While both "writer" and "loader" functions seem to be working, the problem is that every time "loader" is being called, it loads the data from some previously saved file and not the file that is created right now by the "writer". If the user wants the new saved data to be loaded into text fields, he needs to close and reopen the app again. To explain the situation better, I placed some scenario after the codes. Any ideas what is wrong and what can be done?
Here is the code that I'm using to put the info into the file, and it works fine:
public void writer(View view){
try {
FileOutputStream fos = openFileOutput("myfilename", Context.MODE_WORLD_WRITEABLE | Context.MODE_WORLD_READABLE);
PrintStream prntst = new PrintStream(fos);
txtEditor=(EditText)findViewById(R.id.editText1);
prntst.println (txtEditor.getText().toString());
txtEditor=(EditText)findViewById(R.id.EditText02);
prntst.println (txtEditor.getText().toString());
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
And here is the code I'm using to read the info from file to some ArrayList, then this ArrayList is used to fill up the textfields, this is also working fine (fine means without error):
public void reader(View view){
try {
BufferedReader inputReader = new BufferedReader(new InputStreamReader(openFileInput("myfilename")));
Scanner scanner = new Scanner(inputReader);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
bld.add(line);
}
inputReader.close();
scanner.close();
txtEditor=(EditText)findViewById(R.id.editText1);
txtEditor.setText(bld.get(0));
txtEditor=(EditText)findViewById(R.id.EditText02);
txtEditor.setText(bld.get(1));
} catch (IOException e) {
e.printStackTrace();
txtEditor=(EditText)findViewById(R.id.editText1);
bld.add((txtEditor.getText().toString()));
txtEditor=(EditText)findViewById(R.id.EditText02);
bld.add((txtEditor.getText().toString()));
}
}
Scenario:
User opens the app, there are some default values in text fields (two textfields), the user changes the values to 2 and 3 respectively, and touches the save button.
User changes the values again but instead of touching the save button he hits the load button, now the app is supposed to load 2 and 3 into fields (which are saved) but instead, it loads the defaults values.
User closes the app and reopens them, this time 2 and 3 are shown as default in textfields. Seems like the "loader" NOW is reading the data from the previously saved file.
User changes the values from "2 and 3" to "13 and 14" and hits save and load button respectively, but 2 and 3 are loaded into fields.
User closes and reopens the app again, this time 13 and 14 are shown.
PS. the variable bld is global and defined in the MainActivity:
ArrayList<String> bld = new ArrayList<String>();
Thank you,
The problem may be with the global ArrayList variable 'bld'. It's OK to define it globally, But initialize it locally.
The problem is that, you are calling as bld.get(0), But the new values are appended after it.
Add the line bld = new ArrayList<String>();
inside your 'reader' function.
In the writer method you're closing the file output stream:
fos.close();
But surely you should be closing the print stream instead.
prntst.close();
Closing the print stream will flush the stream and then close the underlying output stream. When you close the output stream, it won't know anything about the print stream constructed on top of it, so won't know to flush it.
Related
What I am trying to do is write a record to new line in my text file. Every time someone clicks sign up on my program, I want to call a method that opens a file and adds a record. This is what I have now:
To open the file:
try {
l = new Formatter("chineses.txt");
System.out.println("Did create");
} catch (Exception e){
System.out.println("Did not create");
}
To add the record:
public void addRecord(){
l.format("%s", nameField.getText());
}
Every time I put in a name in the name field and click sign up in my GUI, it always replaces whatever is on the first line in the text file.
How can I make it write to the second line while retaining what is on the first line?
Have you thought about using RandomAccessFile? You can seek to the end, then write.
According to the javadoc a formater created with a single String argument will first empty the file (truncate to zero length) before writing to it. This is why your file is not appended to. The program first removes whatever is in the file and then writes the new content to it when you call l.format().
What you probably want to do is format your data to a String using Formatter(). Open your record file for appending and then write that string to the file. This link should have plenty of details on how you might do this. (I googled "java open and write a file" to find that resource)
I am trying to add a way to save data to the android phone for my app. In the surfaceOnDestroyed I have added the following code.
try {
outputStream = getContext().openFileOutput("data.txt", Context.MODE_PRIVATE);
outputStream.write(current.getBytes());
outputStream.close();
System.out.println(current + " saved");
} catch(Exception e) {
e.printStackTrace();
}
Current is a string variable that I call earlier in my code that I print out here to show what it is when I am writing to the file. Each time I get that the variable is 2.
The data.txt file contains one line with a "0" initially placed in the file because the program reads from the file when the application is started.
When I check the data file after I destroy the object, the 0 is still in the file and has not changed to the 2.
I'm not sure what other information might be needed to solve this issue but I can not figure it out. Help much appreciated.
I am trying to clear the contents of a file I made in java. The file is created by a PrintWriter call. I read here that one can use RandomAccessFile to do so, and read somewhere else that this is in fact better to use than calling a new PrintWriter and immediately closing it to overwrite the file with a blank one.
However, using the RandomAccessFile is not working, and I don't understand why. Here is the basic outline of my code.
PrintWriter writer = new PrintWriter("temp","UTF-8");
while (condition) {
writer.println("Example text");
if (clearCondition) {
new RandomAccessFile("temp","rw").setLength(0);
// Although the solution in the link above did not include ',"rw"'
// My compiler would not accept without a second parameter
writer.println("Text to be written onto the first line of temp file");
}
}
writer.close();
Running the equivalent of the above code is giving my temp file the contents:(Lets imagine that the program looped twice before clearCondition was met)
Example Text
Example Text
Text to be written onto the first line of temp file
NOTE: writer needs to be able to write "Example Text" to the file again after the file is cleared. The clearCondition does not mean that the while loop gets broken.
You want to either flush the PrintWriter to make sure the changes in its buffer are written out first, before you set the RandomAccessFile's length to 0, or close it and re-open a new PrintWriter to write the last line (Text to be written...). Preferably the former:
if (clearCondition) {
writer.flush();
new RandomAccessFile("temp","rw").setLength(0);
You'll be lucky if opening the file twice at the same time works. It isn't specified to work by Java.
What you should do is close the PrintWriter and open a new one without the 'append' parameter, or with 'append' set to 'false'.
I have text file in Android called "longlat.txt".
The text file contain latitude and longitude.
I save all the latitude and longitude to the text file using buffreader method.
After I finished using this app, I want to exit the app.
Means that I need to clear "longlat.txt" so that later on when I use the app, it will start the app without previous data that already being save to "longlat.txt".
So I provide a button called "Clear data" to clear the text file.
Now I need some ideas to clear "longlat.txt" file when user click "Clear data" button.
The only method that I'd used to clear the text file is I need to uninstall the app from my phone and reinstall it again .
I have tried :
public void Clear(View view){
PrintWriter writer;
try {
writer = new PrintWriter("longlat.txt");
writer.print("");
writer.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
After I clicked it, I want to check whether the text file already clear or not with click "Update" button, but when I click "Update" button, it still shows the old text file.
When you are closing the program (or any time you want to clear the file), you can simply just write empty data to the file, like so;
PrintWriter writer = new PrintWriter(file);
writer.print("");
writer.close();
My problem is saving documents in Netbeans. I created a program using Java in Netbeans. At first you register (at the click on register button a new user Map is created with the name of the user), then you login with your user name and your password. When you are logged in, the program displays a new window where you can create documents. You can write text in TextArea. Then when you're finished with writing your text you click on Save button and the text you've written saves in a document named after the text you've given in a jTextField. So for every different login the absolute path changes.
This is my code in submit button:
//ccc is the name of user map
String ccc = LogIn.uporabnik1;
try{
FileWriter writer = new FileWriter("C:\\Users\\ALEKS\\Documents\\NetBeansProjects\\EasyEdit\\"+ccc+"\\"+FileName+".txt");
BufferedWriter bw = new BufferedWriter (writer);
jTextArea1.write(bw);
bw.close();
jTextArea1.setText("");
jTextArea1.requestFocus();
writer.close();
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
It looks like there is a typo with an extra space in your path.
Note that as an alternative, if you use Java 7+, you can also use the Paths utility class to generate paths without having to deal with os specific separators (\\ or /):
Path path = Paths.get("C:/Users/ALEKS/Documents/NetBeansProjects/EasyEdit/"
+ ccc + "/" + FileName + ".txt");
And to write a string to a file:
String text = jTextArea1.getText();
Files.write(path, text.getBytes("UTF-8"));
That makes your code shorter and you don't have to manually create and close the streams.
Finally, for long-ish operations, you should not use the GUI thread but use a background thread instead or you application will become unresponsive as the save operation is in progress.