RENAMING a file in java - java

I am using the following code but I am not able to rename the file.There is no such file newname.txt in the system as well. I am using JRE6. Please help me out! Also I have tried to rename using Files class, That too isn't working.
File f1 = new File("oldname.txt");
File f2 = new File("newname.txt");
boolean b = f1.renameTo(f2);
The same code gets execute on SunOs UNIX but not on my windows 7. Why is it so ? Can I do something to execute it on my local machine?

File path to oldname.txt is not correct, Try giving the absolute path and check it works like "c:\oldname.txt"
File f1 = new File("c:\\oldname.txt");
File f2 = new File("c:\\newname.txt");
boolean b = f1.renameTo(f2);
at the end print the value of b

Ref: Rename a file using Java (edited little bit to fit your requirment)
File f1 = new File("oldname.txt");
File f2 = new File("newname.txt");
if (!f1.exists())
throw new java.io.FileNotFoundException("file not found");
if (f2.exists())
throw new java.io.IOException("file exists");
// Rename file (or directory)
boolean success = f1.renameTo(f2);
if (!success) {
// File was not successfully renamed
}

Related

Unable to save the uploaded file into specific directory

I want to upload files and save them into specific directory.And i am new to files concept.When i uploading files from my page they are saved in another directory(C:\Users\ROOTCP~1\AppData\Local\Temp\multipartBody989135345617811478asTemporaryFile) and not in specified directory.I am unable to set it.Please help me in finding a solution.For all help thanks in advance.
public static Result uploadHoFormsByHeadOffice() throws Exception {
Logger.info("#C HoForms -->> uploadHoFormsByHeadOffice() -->> ");
final String basePath = System.getenv("INVOICE_HOME");
play.mvc.Http.MultipartFormData body = request().body()
.asMultipartFormData(); // get Form Body
StringBuffer fileNameString = new StringBuffer(); // to save file path
// in DB
String formType = body.asFormUrlEncoded().get("formType")[0];// get formType from select Box
FilePart upFile = body.getFile("hoFiles");//get the file details
String fileName = upFile.getFilename();//get the file name
String contentType = upFile.getContentType();
File file = upFile.getFile();
//fileName = StringUtils.substringAfterLast(fileName, ".");
// path to Upload Files
File ftemp= new File(basePath +"HeadOfficeForms\\"+formType+"");
//File ftemp = new File(basePath + "//HeadOfficeForms//" + formType);
File f1 = new File(ftemp.getAbsolutePath());// play
ftemp.mkdirs();
file.setWritable(true);
file.setReadable(true);
f1.setWritable(true);
f1.setReadable(true);
//HoForm.create(fileName, new Date(), formType);
Logger.info("#C HoForms -->> uploadHoFormsByHeadOffice() <<-- Redirecting to Upload Page for Head Office");
return redirect(routes.HoForms.showHoFormUploadPage());
}
}
I really confused why the uploaded file is saved in this(C:\Users\ROOTCP~1\AppData\Local\Temp\multipartBody989135345617811478asTemporaryFile) path.
You're almost there.
File file = upFile.getFile(); is the temporary File you're getting through the form input. All you've got to do is move this file to your desired location by doing something like this: file.renameTo(ftemp).
Your problem in your code is that you're creating a bunch of files in memory ftemp and f1, but you never do anything with them (like writing them to the disk).
Also, I recommend you to clean up your code. A lot of it does nothing (aforementioned f1, also the block where you're doing the setWritable's). This will make debugging a lot easier.
I believe when the file is uploaded, it is stored in the system temporary folder as the name you've provided. It's up to you to copy that file to a name and location that you prefer. In your code you are creating the File object f1 which appears to be the location you want the file to end up in.
You need to do a file copy to copy the file from the temporary folder to the folder you want. Probably the easiest way is using the apache commons FileUtils class.
File fileDest = new File(f1, "myDestFileName.txt");
try {
FileUtils.copyFile(ftemp, fileDest);
}
catch(Exception ex) {
...
}

Java better way to delete file if exists

We need to call file.exists() before file.delete() before we can delete a file E.g.
File file = ...;
if (file.exists()){
file.delete();
}
Currently in all our project we create a static method in some util class to wrap this code. Is there some other way to achieve the same , so that we not need to copy our utils file in every other project.
Starting from Java 7 you can use deleteIfExists that returns a boolean (or throw an Exception) depending on whether a file was deleted or not. This method may not be atomic with respect to other file system operations. Moreover if a file is in use by JVM/other program then on some operating system it will not be able to remove it. Every file can be converted to path via toPath method . E.g.
File file = ...;
boolean result = Files.deleteIfExists(file.toPath()); //surround it in try catch block
file.delete();
if the file doesn't exist, it will return false.
There's also the Java 7 solution, using the new(ish) Path abstraction:
Path fileToDeletePath = Paths.get("fileToDelete_jdk7.txt");
Files.delete(fileToDeletePath);
Hope this helps.
Apache Commons IO's FileUtils offers FileUtils.deleteQuietly:
Deletes a file, never throwing an exception. If file is a directory, delete it and all sub-directories.
The difference between File.delete() and this method are:
A directory to be deleted does not have to be empty.
No exceptions are thrown when a file or directory cannot be deleted.
This offers a one-liner delete call that won't complain if the file fails to be deleted:
FileUtils.deleteQuietly(new File("test.txt"));
I was working on this type of function, maybe this will interests some of you ...
public boolean deleteFile(File file) throws IOException {
if (file != null) {
if (file.isDirectory()) {
File[] files = file.listFiles();
for (File f: files) {
deleteFile(f);
}
}
return Files.deleteIfExists(file.toPath());
}
return false;
}
if you have the file inside a dirrectory called uploads in your project. bellow code can be used.
Path root = Paths.get("uploads");
File existingFile = new File(this.root.resolve("img.png").toUri());
if (existingFile.exists() && existingFile.isFile()) {
existingFile.delete();
}
OR
If it is inside a different directory this solution can be used.
File existingFile = new File("D:\\<path>\\img.png");
if (existingFile.exists() && existingFile.isFile()) {
existingFile.delete();
}
Use the below statement to delete any files:
FileUtils.forceDelete(FilePath);
Note: Use exception handling codes if you want to use.
Use Apache Commons FileUtils.deleteDirectory() or FileUtils.forceDelete() to log exceptions in case of any failures,
or FileUtils.deleteQuietly() if you're not concerned about exceptions thrown.
Generally We create the File object and check if File Exist then delete.
File f1 = new File("answer.txt");
if(f1.exists()) {
f1.delete();
}
OR
File f2 = new File("answer.txt");
f2.deleteOnExit();
If you are uses the Apache Common then below are the option using which you can delete file and directory
File f3 = new File("answer.txt");
FileUtils.deleteDirectory(f3);
This method throws the exception in case of any failure.
OR
File f4 = new File("answer.txt");
FileUtils.deleteQuietly(f4);
This method will not throw any exception.
This is my solution:
File f = new File("file.txt");
if(f.exists() && !f.isDirectory()) {
f.delete();
}
File xx = new File("filename.txt");
if (xx.exists()) {
System.gc();//Added this part
Thread.sleep(2000);////This part gives the Bufferedreaders and the InputStreams time to close Completely
xx.delete();
}

Create a folder and a file with Java in Ubuntu

Here is what I wanna do:
Check if a folder exists
If it does not exists, create the folder
If it doest exists do nothing
At last create a file in that folder
Everything is working fine in Windows 7, but when I run the application in Ubuntu it doesn't create the folder, it is just creating the file with the folder name, example: (my file name is xxx.xml and the folder is d:\temp, so in Ubuntu the file is generated at d: with the name temp\xxx.xml). Here is my code:
File folder = new File("D:\\temp");
if (folder.exists() && folder.isDirectory()) {
} else {
folder.mkdir();
}
String filePath = folder + File.separator;
File file = new File(filePath + "xxx.xml");
StreamResult result = new StreamResult(file);
transformer.transform(source, result);
// more code here
Linux does not use drive letters (like D:) and uses forward slashes as file separator.
You can do something like this:
File folder = new File("/path/name/of/the/folder");
folder.mkdirs(); // this will also create parent directories if necessary
File file = new File(folder, "filename");
StreamResult result = new StreamResult(file);
You directory (D:\temp) is nos appropriate on Linux.
Please, consider using linux File System, and the File.SEPARATOR constant :
static String OS = System.getProperty("OS.name").toLowerCase();
String root = "/tmp";
if (OS.indexOf("win") >= 0) {
root="D:\\temp";
} else {
root="/";
}
File folder = new File(ROOT + "dir1" + File.SEPARATOR + "dir2");
if (folder.exists() && folder.isDirectory()) {
} else {
folder.mkdir();
}
Didn't tried it, but whould work.
D:\temp does not exists in linux systems (what I mean is it interprets it as if it were any other foldername)
In Linux systems the file seperator is / instead of \ as in case of Windows
so the solution is to :
File folder = new File("/tmp");
instead of
File folder = new File("D:\\temp");
Before Java 7 the File API has some possibilities to create a temporary file, utilising the operating system configuration (like temp files on a RAM disk). Since Java 7 use the utility functions class Files.
Consider both solutions using the getProperty static method of System class.
String os = System.getProperty("os.name");
if(os.indexOf("nix") >= 0 || os.indexOf("nux") >= 0 || os.indexOf("aix") > 0 ) // Unix
File folder = new File("/home/tmp");
else if(os.indexOf("win") >= 0) // Windows
File folder = new File("D:\\temp");
else
throw Exception("your message");
On Unix-like systems no logical discs. You can try create on /tmp or /home
Below code for create temp dirrectory in your home directory:
String myPathCandidate = System.getProperty("os.name").equals("Linux")? System.getProperty("user.home"):"D:\\";
System.out.println(myPathCandidate);
//Check write permissions
File folder = new File(myPathCandidate);
if (folder.exists() && folder.isDirectory() && folder.canWrite()) {
System.out.println("Create directory here");
} else {System.out.println("Wrong path");}
or, for /tmp - system temp dicecrory. Majority of users can write here:
String myPathCandidate = System.getProperty("os.name").equals("Linux")? System.getProperty("java.io.tmpdir"):"D:\\";
Since Java 7, you can use the Files utility class, with the new Path class. Note that exception handling has been omitted in the examples below.
// uses os separator for path/to/folder.
Path file = Paths.get("path","to","file");
// this creates directories in case they don't exist
Files.createDirectories(file.getParent());
if (!Files.exists(file)) {
Files.createFile(file);
}
StreamResult result = new StreamResult(file.toFile());
transformer.transform(source, result);
this covers the generic case, create a folder if it doesn't exist and a file on that folder.
In case you actually want to create a temporary file, as written in your example, then you just need to do the following:
// this create a temporary file on the system's default temp folder.
Path tempFile = Files.createTempFile("xxx", "xml");
StreamResult result = new StreamResult(Files.newOutputStream(file, CREATE, APPEND, DELETE_ON_CLOSE));
transformer.transform(source, result);
Note that with this method, the file name will not correspond exactly to the prefix you used (xxx, in this case).
Still, given that it's a temp file, that shouldn't matter at all. The DELETE_ON_CLOSE guarantees that the file will get deleted when closed.

I can't locate files which created by program

I created a desktop project in netbeans, in the project folder I have three files : file.txt, file2.txt and file3.txt, in the load of the program I want to call these three files, and this is the code I tried :
public void run() {
Path path = Paths.get("file.txt");
Path path2 = Paths.get("file2.txt");
Path path3 = Paths.get("file3.txt");
if(Files.exists(path) && Files.exists(path2) && Files.exists(path3)) {
lireFichiers();
}else{
JOptionPane.showConfirmDialog(null, "Files didn't found !");
}
}
but when I run my program I get the message : "Files didn't found !" which means he didn't found those files.
those files are created by this code :
File file = new File("Id.txt");
File file2 = new File("Pass.txt");
File file3 = new File("Remember.txt");
The following three lines will only create file handlers for your program to use. This will not create a file by itself. If you are using the handler to write it will also create a file for you provided you close correctly after writing.
File file = new File("Id.txt");
File file2 = new File("Pass.txt");
File file3 = new File("Remember.txt");
So, a sample code will look like:
File file = new File("Id.txt");
FileWriter fw = new FileWriter(file);
try
{
// write to file
}
finally
{
fw.close();
}
If the file is in the root of your project, this should work:
Path path = Paths.get("foo.txt");
System.out.println(Files.exists(path)); // true
Where exatlcy are the files you want to open in your project?
Please specify the language you use.
Generally you could search the file to see whether the files are in the program bootup folder. For webapps you should pay attention to the "absolute path and the relative path".
=========Edit============
If you are using Jave, then the file should be write out using FileWriter.close() before you can find them in your hard disk.
Ref
Thank you all for your help, I just tried this :
File file = new File("Id.txt");
File file2 = new File("Pass.txt");
File file3 = new File("Remember.txt");
if(file.exists() && file2.exists() && file3.exists()){
// manipulation
}
and it works

Java and JSF, Checking if a file exists on the server

I have a web application, and I'm trying to return a boolean, of a .zip file that gets (successfully) generated on the server.
Locally I run this on Eclipse with Tomcat on Windows, but I am deploying it to a Tomcat Server on a Linux machine.
//.zip is generated successfully on the SERVER by this point
File file1 = new File("/Project/zip/theZipFile.zip");
boolean exists = file1.exists();// used to print if the file exists, returns false
if (exists)
fileLocation = "YES";
else
fileLocation = "No";
When I do this, it keeps returning false on the debugger and on my page when I print it out. I am sure it has something to do with file paths, but I am unsure.
Once I get the existence of the zip confirmed, I can easily use File.length() to get what I need.
Assume all getters and setters are in existence, and the JSF prints. It is mainly the Java backend I am having a slight issue with.
Thanks for any help! :)
Your path is not good. Try remove the leading / to fix the problem
See the test code for explanations :
import java.io.*;
public class TestFile {
public static void main(String[] args) {
try {
//Creates a myfile.txt file in the current directory
File f1 = new File("myfile.txt");
f1.createNewFile();
System.out.println(f1.exists());
//Creates a myfile.txt file in a sub-directory
File f2 = new File("subdir/myfile.txt");
f2.createNewFile();
System.out.println(f2.exists());
//Throws an IOException because of the leading /
File f3 = new File("/subdir/myfile.txt");
f3.createNewFile();
System.out.println(f3.exists());
} catch(IOException e) {
System.out.println(e.getMessage());
}
}
}
Debug using this statement
System.out.println("Actual file location : " + file1.getAbsolutePath());
This will tell you the absolute path of the file it's looking for

Categories

Resources