Editing file in External Storage - java

In my app, I am writing a file and storing it in external storage
But everytime I want to edit it, I have to get the data of file, delete it and then recreate it using the new data.
But is there any way to directly edit a existing file instead of deleteing and recreating it?

Thanks to blackbelt for helping me out.
Here is how to do this -
File gpxfile = new File(File address, "filename.txt");
BufferedWriter bW;
try {
bW = new BufferedWriter(new FileWriter(gpxfile));
bW.write("file text");
bW.newLine();
bW.flush();
bW.close();
} catch (IOException e) {
e.printStackTrace();
}
This will rewrite the file. If you just want to add a line instead of replacing the whole thing, then replace
bW = new BufferedWriter(new FileWriter(gpxfile));
with
bW = new BufferedWriter(new FileWriter(gpxfile, true));

Related

Unable to rename and delete file in Java

I am doing a project in Java using NetBeans and I need to modify a file. So I overwrite the whole file in another temporary file, but at the end I could not rename the temporary file or delete the main file. Any solutions?
File tf = new File("F:\\nb\\project_inventory\\temp.tmp");
FileReader fr = new FileReader("F:\\nb\\project_inventory\\Employee_info.txt");
BufferedReader br =new BufferedReader(fr);
FileWriter fw = new FileWriter(tf);
PrintWriter bw =new PrintWriter(fw);
String line;
while((line=br.readLine())!=null)
{
if(line.contains(del_id)) continue;
bw.println(line);
}
bw.close();
fw.close();
br.close();
fr.close();
File real =new File("F:\\nb\\project_inventory\\Employee_info.txt");
real.delete();
tf.renameTo(real);
I just tried 5 of the above project lines as below and got the desired result,
File real =new File("F:\\nb\\project_inventory\\Employee_info.txt");
real.delete();
File tf = new File("F:\\nb\\project_inventory\\temp.tmp");
try{
tf.createNewFile(); // for creating the new file
}
catch(IOException e){
e.printstacktrace();
}
File real =new File("F:\\nb\\project_inventory\\Employee_info.txt");
tf.renameTo(real);
Employee_info.txt is getting deleted as well as temp.tmp is getting renamed as Employee_info.txt too.
Also, it is always recommended to put the code for delete/rename inside try/catch block like below:
try{
File real =new File("F:\\nb\\project_inventory\\Employee_info.txt");
real.delete();
}
catch(IOException e){
e.printstacktrace();
}
Please provide the error message, to help you further.

Deleting an existing file in java and renaming the temp file [duplicate]

I am doing a project in Java using NetBeans and I need to modify a file. So I overwrite the whole file in another temporary file, but at the end I could not rename the temporary file or delete the main file. Any solutions?
File tf = new File("F:\\nb\\project_inventory\\temp.tmp");
FileReader fr = new FileReader("F:\\nb\\project_inventory\\Employee_info.txt");
BufferedReader br =new BufferedReader(fr);
FileWriter fw = new FileWriter(tf);
PrintWriter bw =new PrintWriter(fw);
String line;
while((line=br.readLine())!=null)
{
if(line.contains(del_id)) continue;
bw.println(line);
}
bw.close();
fw.close();
br.close();
fr.close();
File real =new File("F:\\nb\\project_inventory\\Employee_info.txt");
real.delete();
tf.renameTo(real);
I just tried 5 of the above project lines as below and got the desired result,
File real =new File("F:\\nb\\project_inventory\\Employee_info.txt");
real.delete();
File tf = new File("F:\\nb\\project_inventory\\temp.tmp");
try{
tf.createNewFile(); // for creating the new file
}
catch(IOException e){
e.printstacktrace();
}
File real =new File("F:\\nb\\project_inventory\\Employee_info.txt");
tf.renameTo(real);
Employee_info.txt is getting deleted as well as temp.tmp is getting renamed as Employee_info.txt too.
Also, it is always recommended to put the code for delete/rename inside try/catch block like below:
try{
File real =new File("F:\\nb\\project_inventory\\Employee_info.txt");
real.delete();
}
catch(IOException e){
e.printstacktrace();
}
Please provide the error message, to help you further.

Java - Copy long text of a text file to another

I have one txt file with a very, very long text and I want to read, make some changes and copy that text to other txt files. The problem is that I can't read the file by the BufferedReader because I'd have to store the text in a variable, but that can't be done due to capacity and then write it to another file... Is there a way this can be done?
BuffereReader(Writer) works fine for this tasks (reading,writing large files)
BufferedWriter bw=null ;
BufferedReader br=null;
try{
br = new BufferedReader(new FileReader(new File("e:/temp/1.txt")));
bw = new BufferedWriter(new FileWriter(new File("e:/temp/2.txt")));
String st="";
while((st=br.readLine())!=null){
bw.write(st.replace("a","b"));
bw.newLine();
}
bw.close();
br.close();
}catch(Exception e)
{
e.printStackTrace();
}finally
{
}

Saving String Input on Android

Right, I've been trying to find a solution to this for a good while, but it's just not working for some reason.
In short, what I want to do is save every input String the user inputs into a file. Every time the activity is created again, I want to re-input these strings into a new instance of an object.
This code is what I use to create the file and read info from it, used in the onCreate() method of activity
try {
String brain = "brain";
File file = new File(this.getFilesDir(), brain);
if (!file.exists()) {
file.createNewFile();
}
BufferedReader in = new BufferedReader(new FileReader(file));
String s; // This feeds the object MegaAndroid with the strings, sequentially
while ((s = in.readLine()) != null) {
MegaAndroid.add(s);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
After that, every time the user inputs some text, the strings are saved onto the file:
try {
String brain = "brain";
File file = new File(this.getFilesDir(), brain);
if (!file.exists()) {
file.createNewFile();
}
BufferedWriter out = new BufferedWriter(new FileWriter(file));
out.write(message); // message is a string that holds the user input
out.close();
} catch (IOException e) {
e.printStackTrace();
}
For some reason, however, every time the application is killed, the data is lost.
What am I doing wrong?
EDIT: Also, if I were to access this file from another class, how can I?
As we discussed in the commend section the chief problem with the code is that your execution of FileWriter occurred prior to your FileReader operation while truncating the file. For you to maintain the file contents you want to set the write operation to an append:
BufferedWriter out = new BufferedWriter(new FileWriter(file,true));
out.write(message);
out.newLine();
out.close();
However, if every entry on the EditText is received then shipped into the file you'll just be writing data byte after byte beside it. It is easy to get contents similar to
This is line #1This is line #2
Instead of the desired
This is line #1
This is line #2
which would be corrected by having the BufferedWriter pass a newline after each write to the file.
This is what I do for file reading.
try{
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/whereyouwantfile");
dir.mkdirs();
Log.d(TAG,"path: "+dir.getAbsolutePath());
File file = new File(dir, "VERSION_FILENAME");
FileInputStream f = new FileInputStream(file);
//FileInputStream fis = context.openFileInput(VERSION_FILENAME);
BufferedReader reader = new BufferedReader(new InputStreamReader(f));
String line = reader.readLine();
Log.d(TAG,"first line versions: "+line);
while(line != null){
Log.d(TAG,"line: "+line);
//Process line how you need
line = reader.readLine();
}
reader.close();
f.close();
}
catch(Exception e){
Log.e(TAG,"Error retrieving cached data.");
}
And the following for writing
try{
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/whereyouwantfile");
dir.mkdirs();
File file = new File(dir, "CONTENT_FILENAME");
FileOutputStream f = new FileOutputStream(file);
//FileOutputStream fos = context.openFileOutput(CONTENT_FILENAME, Context.MODE_PRIVATE);
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(f));
Set<String> keys = Content.keySet();
for(String key : keys){
String data = Content.get(key);
Log.d(TAG,"Writing: "+key+","+data);
writer.write(data);
writer.newLine();
}
writer.close();
f.close();
}
catch(Exception e){
e.printStackTrace();
Log.e(TAG,"Error writing cached data.");
}
You can use the private mode if you don't want the rest of the world to be able to see your files, but it is often useful to see them when debugging.

append to file android

hey there, i need to append to my file but it is not working, it keeps overwriting the file, can anyone please tell me what is wrong:
public void generateNoteOnSD(String sBody){
try
{
File root = new File(Environment.getExternalStorageDirectory(), "AdidasParticipants");
if (!root.exists()) {
root.mkdirs();
}
File gpxfile = new File(root, "participants.txt");
BufferedWriter bW;
bW = new BufferedWriter(new FileWriter(gpxfile));
bW.write(sBody);
bW.newLine();
bW.flush();
bW.close();
//Toast.makeText(mContext, "Tus datos han sido guardados", Toast.LENGTH_SHORT).show();
}
catch(IOException e)
{
e.printStackTrace();
// importError = e.getMessage();
// iError();
}
}
Thanks in advance.
You can fix it by changing the line where you assign the BufferedWriter:
bW = new BufferedWriter(new FileWriter(gpxfile, true));
When you open a file using the FileWriter constructor that only takes in a File, it will overwrite what was previously in the file. Supplying the second parameter as true tells the FileWriter that you want to append to the end of it.

Categories