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();
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 was wondering how to make the program show a specific text it's ran by the first time, I know in android programming, a way to do this is by making a specification in the manifest. So I hope you'd understand me and can help me.
If you need to create a flag file use this
String FLAG_PTH="path/to file/flag.txt";
String flag="";
Use this code at load event of the page
try{
byte[] bfr=new byte[50];
FileInputStream IPS=new FileInputStream(COL_PTH);
int tn=0;
int nread=0;
while((nread=IPS.read(bfr))!=-1){
String clr=new String(bfr);
flag=clr;
}
IPS.close();
}
catch(FileNotFoundException fe){
System.out.println("ERR:9"+fe);
}
catch(IOException IOe){
System.out.println("ERR:10"+IOe);
}
if(flag=="True"){
// type your code for showing some text,or whatever it is.
try{
FileWriter FW=new FileWriter(FLAG_PTH);
BufferedWriter BF_Wr=new BufferedWriter(FW);
BF_Wr.write("TRUE");
BF_Wr.close();
}
catch(IOException e){
System.out.println("ERR:06"+e);
}
}
else {
//hide text and go through normal open
}
Well, I would have a text file with the word false in it,right at the top.Then in the programme you read that line, if it reads true then make it display whatever text you wish.After that you delete the file and make a new one(inside the if statement) with the same name only with true at the top this time.Therefore that if statement can only run again if that text file is changed to true.This is going to need buffered streams so read up on that: https://docs.oracle.com/javase/tutorial/essential/io/index.html .Alsojust a piece of advice keep all of your resources inside your jar file in a source folder as best as you can(its a lot less easier for users to mess with) doing this will cause you to need to use getResourceAsStream : https://m.youtube.com/watch?v=yksgU4SxoJY .I assure you it won't take long to go throught this.
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.
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.