java - File length after rename - java

a simple question, I have the following java code:
File file = new File("myFile.xls");
file.renameTo("mySecondFile.xls");
System.out.println(file.length());
If I run it, I see that the file has changed of name correctly, but strangely file.length() returns 0 (And the file is not empty)
Any idea?
Thank you

File is immutable. It will always point to the filepath you created it with.
So when you rename your file, the file to which your File object points doesn't exist anymore (it was renamed) and you get the file length of 0.
See also the javadoc.

Try this:
File file = new File("myFile.xls");
file.renameTo("mySecondFile.xls");
File file2 = new File("mySecondFile.xls");
System.out.println(file2.length());

Related

No matter what I do, I can't get Java to recognize the filepath for a text file

I've been trying to set up a Scanner to use a File as an input, but it doesn't seem to recognize the filepath. The file exists in the same folder as my .java files.
File errorList = new File("Errors.txt");
Scanner errorIn = new Scanner(errorList);
This results in a FileNotFoundException.
What am I doing wrong, and how can I fix this?
One other approach you could try is, execute the below code in your eclipse (from any of your class), and see where the hello.txt is created, so you get an idea of where Java is looking for the file.
new File("hello.txt").createNewFile();
Then you could either put your Errors.txt in that location or provide the corresponding relative location.

How to rename file forth and back in java

I want to rename a file name xxx.docx to xxx.docx.zip then rename it back to xxx.docx in Java.
Here is my code.
File file = new File(path);
File file2 = new File(path+".zip");
file.renameTo(file2);
File file3 = new File(file.getPath());
file2.renameTo(file3);
It won't work. Thank you.
Edit : The problem is I forgot to close the doc before renaming it.
The code like that works. Most probably some other process has locked the file and made it read only. You have either opened it in word (since it is docx file) or something like that. Maybe it is in a readonly location.
The code is working though. Try with different file and you will see it is fine (I tried it).

Files.copy renaming files

Was hoping you could look at some code for me:
public void Copy(Path sourcepath,
Path targetpath) throws IOException {
DateFormat dateFormat = new SimpleDateFormat("yyyymmdd");
File origfile = targetpath.toFile(); // Changes targetpath to file
String name = origfile.getName(); // Gets the name of the file to be updated
File file1 = new File(targetpath.toString() + "." + dateFormat.format(Calendar.getInstance().getTime())); //Create a new file instance with the name of the old file + date
origfile.renameTo(file1); //Rename the original file
origfile.createNewFile(); //Backup the original file
Files.delete(targetpath); //Delete the original file
Files.copy(sourcepath, targetpath);
}
Now everything works, the backing up works and the copying works. My original intention was to rename file being copied to the file being backed up. (hence the string name = origfile.getName();
This was my code:
File file2 = new File(name);
File srcfile = sourcepath.toFile();
srcfile.renameTo(file2);
Now, that worked up to a point, after a while I started getting IOException errors, so after a few hours of struggling. I gave up and just deleted that renaming part.
Lo and behold it still renames the file when being copied.
Now my question: Does Files.copy do it? Is there some mysterious thing happening here? It does EXACTLY what I want it to do, but I am baffled as hell. Why is my code working?
and yes I want to know, in case it breaks or stops working. I can't have something work and not know why!
EDIT:
Sorry was in a bit of a rush when posting, let me pose my question a bit more clearer:
my intention was to have my sourcepath renamed to the original name of the file that is being backed up. I had code to rename it, but it threw an IOException so I deleted it. I only used Files.Copy, so I assumed sourcepath would retain it's original value, and just copy for each instance in a for loop I have. But no, it renames perfectly to the original of each file being backed up. Where and how?
Figured it out! Wooo!
Because I converted the targetpath to a file, backed it up and deleted it this happened:
when I used Files.copy(srcpath,targetpath) srcpath took targetpath's name (the file is deleted but the original path is still there because nothing happened to it)
So basically: two paths were sent to my method, my method created a backup file and deleted the original file (not the path) of the original path. (which would be c:\work\testorigfile e.g.)
Thus when I used Files.copy(srcpath,targetpath) it worked exactly as I wanted it. The answer WAS in the javadoc (in a sense) so thanks for all the tips guys!

Java: File output help

Fixed: Instead of calling isFile() I used exists() and it seems to be working fine. If possible could someone explain why this change worked?
I'm attempting to write out to an excel file but am having a problem when trying to create that file if the name already exists.
Basically I am taking a file that is uploaded to a server, reading it, and then outputting a report file in a new location with the same filename. I tried to do this by simply checking if the file already existed and then adding a number onto the filename. My code works if the file doesn't exist or if it exists without a number (e.g. filename.xls). If a file exists with the name "filename1.xls" the server just seems to hang when trying to write the file. What can do to fix this?
Here is my code:
String destination = "c:/apache-tomcat-7.0.8/webapps/reports/" + fileName.substring( fileName.lastIndexOf("\\")+1, fileName.lastIndexOf(".")) + ".xls";
int filenum = 1;
while (new File(destination).isFile()) {
destination = "c:/apache-tomcat-7.0.8/webapps/reports/" + fileName.substring( fileName.lastIndexOf("\\")+1, fileName.lastIndexOf(".")) + filenum + ".xls";
filenum++;
}
WritableWorkbook workbook = Workbook.createWorkbook(new File(destination));
That will happen if some process is still keeping the file open. E.g. you've created a FileInputStream on the file to read it, but are never calling close() on it after reading.
Unrelated to the problem, the expanded WAR folder is not the best place to use as a permanent storage. All those files in the expanded WAR folder will get lost whenever you redeploy the WAR. Also hardcoding a servletcontainer-specific path in the code makes it totally unportable.
If your actual intent is to return the Excel file on a per-request basis to the client using a servlet, then you should be using
WritableWorkbook workBook = Workbook.createWorkbook(response.getOutputStream());
// ...
This way it writes to the response immediately without the need for an intermediate file.
Use the File.createTempFile(prefix, suffix, directory) API:
String localName = new File(fileName).getName();
String nameNoExt = localName.substring(0, fileName.lastIndexOf("."));
String extension = localName.substring(fileName.lastIndexOf(".")); // need to include the .
File directory = new File("c:/apache-tomcat-7.0.8/webapps/reports/");
File destFile = File.createTempFile(nameNoExt, extension, directory)

Write file in sub-directory in Android

I'm trying to save a file in a subdirectory in Android 1.5.
I can successfully create a directory using
_context.GetFileStreamPath("foo").mkdir();
(_context is the Activity where I start the execution of saving the file) but then if I try to create a file in foo/ by
_context.GetFileStreamPath("foo/bar.txt");
I get a exception saying I can't have directory separator in a file name ("/").
I'm missing something of working with files in Android... I thought I could use the standard Java classes but they don't seem to work...
I searched the Android documentation but I couldn't fine example and google is not helping me too...
I'm asking the wrong question (to google)...
Can you help me out with this?
Thank you!
I understood what I was missing.
Java File classes works just fine, you just have to pass the absolute path where you can actually write files.
To get this "root" directory I used _context.getFilesDir(). This will give you the root of you application. With this I can create file with new File(root + "myFileName") or as Sean Owen said new File(rootDirectory, "myFileName").
You cannot use path directly, but you must make a file object about every directory.
I do not understand why, but this is the way it works.
NOTE: This code makes directories, yours may not need that...
File file = context.getFilesDir();
file.mkdir();
String[] array = filePath.split("/");
for (int t = 0; t < array.length - 1; t++) {
file = new File(file, array[t]);
file.mkdir();
}
File f = new File(file, array[array.length - 1]);
RandomAccessFileOutputStream rvalue = new RandomAccessFileOutputStream(f, append);
Use getDir() to get a handle on the "foo" directory as a File object, and create something like new File(fooDir, "bar.txt") from it.

Categories