Unable to rename and delete file in Java - 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.

Related

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.

How to copy a text file, and print out the original and copied file in Java

I'm doing a program that needs to take a text file (test.txt) and make a copy of it and print it out. So far I am only able to print out the original file. I have searched for a way of doing this but there doesn't seem to be any help that I can understand, I am very new to java. I am at least looking for guidance, not just the full answer.
my code so far...
import java.io.*;
public class Copy{
public static void main(String [] args){
try{
FileInputStream fis = new FileInputStream("test.txt");
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
File a = new File("test.txt");
FileReader fr = new FileReader(a);
File b = new File("Copied.txt");
FileWriter fw = new FileWriter(b);
while(true){
String line = br.readLine();
if(line != null){
System.out.println(line);
} else{
br.close();
break;
}
}
} catch(FileNotFoundException e){
System.out.println("Error: " + e.getMessage());
} catch(IOException e){
System.out.println("Error: " + e.getMessage());
}
}
}
Again any bit of help will be greatly appreciated since I am trying to learn this. Thank you
Normally, I'd recommend using Files.copy just for it's simplicty, but since you need to "print" the content at the same time, we can make use of your code.
First, however, as a general rule of thumb, if you open it, you should close it. This makes sure that you're not leaving resources open which might affect other parts of your code.
See The try-with-resources Statement for more details.
Next, once you've read a line of text from the source file, you actually need to write it to the destination file, for example...
try (BufferedReader br = new BufferedReader(new FileReader("test.txt"))) {
try (BufferedWriter bw = new BufferedWriter(new FileWriter("Copied.txt"))) {
String text = null;
while ((text = br.readLine()) != null) {
System.out.println(text);
bw.write(text);
bw.newLine();
}
}
} catch (FileNotFoundException e) {
System.out.println("Error: " + e.getMessage());
} catch (IOException e) {
System.out.println("Error: " + e.getMessage());
}
You can use Files.copy() if you are using Java 1.7 or higher
File src = "your File";
File dest = "your copy target"
Files.copy(src.toPath(),dest.toPath());
Link to Javadoc
Change your FileWriter into a PrintStream:
PrintStream fw = new PrintStream(b);
Then you should be able to write to that file using:
fw.println(line);

Editing file in External Storage

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));

Writing data to a file

I want to create a folder from inside my app. Inside the folder, I want to create just one file (say recents) where the app will keep writing data line by line on each launch.
private void saveForRecents(String phoneNumber) {
//Need to open File and write the phonenumbers that has been passed into it
try{
File mydir = getDir("recents", 0);
//Creating an internal dir;
File fileWithinMyDir = new File(mydir, "recents");
//Getting a file within the dir.
FileWriter fw = new FileWriter(fileWithinMyDir.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(phoneNumber);
bw.newLine();
bw.flush();
bw.close();
}catch(Exception e){
Toast.makeText(getApplicationContext(), "Failed to write into the file", Toast.LENGTH_LONG).show();
}
}
How do I access the contents of the recents file that is inside my directory mydir? And I want to access the data line by line as I'm writing data line by line. I would really appreciate if someone took their time to explain me how to do it because I need to learn it. Also please let me know if I am doing something wrong.
Based on what you are doing, I think using SharedPreferences is a better way to go. It won't be overwritten by someone else, and it's hidden from someone messing around in a file explorer. Here's a quick example assuming you have your recent phone numbers in some sort of an array. Other methods are possible of course.
SharedPreferences Prefs = getSharedPreferences("RecentPhoneNumbers", MODE_PRIVATE);
Editor e = Prefs.edit();
e.clear();
for (String s : RecentPhoneArray)
{
e.putString(s);
}
e.commit();
Then to load them the next time the application starts or needs a reload:
SharedPreferences Prefs = getSharedPreferences("RecentPhoneNumbers", MODE_PRIVATE);
for (Map.Entry<String, ?> entry : Prefs.getAll().entrySet())
{
String s = entry.getValue().toString();
RecentPhoneArray.add(s);
}
After a long time I figured out the second part of my problem. This might be useful for other users if they come across the same problem.
For Making a custom directory (here recents) and a custom file (here recent)
try
{
File mydir = getDir("recents", 0);
File fileWithinMyDir = new File(mydir, "recent");
//true here lets the data to be added in the same file in the next line
// No value at all or a false will overwrite the file
FileWriter fw = new FileWriter(fileWithinMyDir.getAbsoluteFile(), true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write("Anything you want to write");
bw.newLine();
bw.flush();
bw.close();
}catch(Exception e){
Toast.makeText(getApplicationContext(), "Failed to write into the file", Toast.LENGTH_LONG).show();
}
The following code helps to read the same file(here recent) inside the same directory(here recents)
try
{
File mydir = this.getDir("recents", 0);
File fileWithinMyDir = new File(mydir, "recent");
try
{
// open the file for reading
InputStream instream = new FileInputStream(fileWithinMyDir);
if (instream != null)
{
// prepare the file for reading
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputreader);
String line;
while ((line = buffreader.readLine())!= null)
{
// do something with the line
}
instream.close();
}
}
catch (Exception ex)
{
// print stack trace.
}
finally
{
// close the file.
}
}
catch(Exception e)
{
e.printStackTrace();
}
One important thing to note is that if a directory recents here and file inside it recent here does not exist then it will automatically be created in the first run. From the second run it will start referencing it rather than recreating the whole thing again...
Hope this will help some users

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.

Categories