can file.renameTo replace a existing file? - java

// File (or directory) to be moved
File file = new File("filename");
// Destination directory
File dir = new File("directoryname");
// Move file to new directory
boolean success = file.renameTo(new File(dir, file.getName()));
if (!success) {
// File was not successfully moved
//can it be because file with file name already exists in destination?
}
If the file with name 'filename' already exists in the destination will it be replaced with a new one?

According to Javadoc:
Many aspects of the behavior of this method are inherently platform-dependent: The rename operation might not be able to move a file from one filesystem to another, it might not be atomic, and it might not succeed if a file with the destination abstract pathname already exists. The return value should always be checked to make sure that the rename operation was successful.

From Javadoc:
The rename operation might not be able
to move a file from one filesystem to
another, it might not be atomic, and
it might not succeed if a file with
the destination abstract pathname
already exists.
I tested the following code:
It works the first time, second time it fails as expected.
To move a file you should delete or rename the destination if required.
public class Test {
public static void main(String[] args) throws IOException {
File file = new File( "c:\\filename" );
file.createNewFile();
File dir = new File( "c:\\temp" );
boolean success = file.renameTo( new File( dir, file.getName() ) );
if ( !success ) {
System.err.println( "succ:" + success );
}
}
}

As it is system dependent you should not expect it to behave this or other way. Check it and implement your own logic.

Related

renaming file name inside a zip file

trying to rename internal file within a zip file without having to extract and then re-zip programatically.
example. test.zip contains test.txt, i want to change it so that test.zip will contain newtest.txt(test.txt renamed to newtest.txt, contents remain the same)
came across this link that works but unfortunately it expects test.txt to exist on the system. In the example the srcfile should exist on the server.
Blockquote Rename file in zip with zip4j
Then icame across zipnote on Linux that does the trick but unfortunately the version i have doesnt work for files >4GB.
Any suggestions on how to accomplish this? prefereably in java.
This should be possible using Java 7 Zip FileSystem provider, something like:
// syntax defined in java.net.JarURLConnection
URI uri = URI.create("jar:file:/directoryPath/file.zip");
try (FileSystem zipfs = FileSystems.newFileSystem(uri, Collections.<String, Object>emptyMap())) {
Path sourceURI = zipfs.getPath("/pathToDirectoryInsideZip/file.txt");
Path destinationURI = zipfs.getPath("/pathToDirectoryInsideZip/renamed.txt");
Files.move(sourceURI, destinationURI);
}
Using zip4j, I am modifying and re-writing the file headers inside of the central directory section to avoid rewriting the entire zip file:
ArrayList<FileHeader> FHs = (ArrayList<FileHeader>) zipFile.getFileHeaders();
FHs.get(0).setFileName("namename.mp4");
FHs.get(0).setFileNameLength("namename.mp4".getBytes("UTF-8").length);
zipFile.updateHeaders ();
//where updateHeaders is :
public void updateHeaders() throws ZipException, IOException {
checkZipModel();
if (this.zipModel == null) {
throw new ZipException("internal error: zip model is null");
}
if (Zip4jUtil.checkFileExists(file)) {
if (zipModel.isSplitArchive()) {
throw new ZipException("Zip file already exists. Zip file format does not allow updating split/spanned files");
}
}
long offset = zipModel.getEndCentralDirRecord().getOffsetOfStartOfCentralDir();
HeaderWriter headerWriter = new HeaderWriter();
SplitOutputStream splitOutputStream = new SplitOutputStream(new File(zipModel.getZipFile()), -1);
splitOutputStream.seek(offset);
headerWriter.finalizeZipFile(zipModel, splitOutputStream);
splitOutputStream.close();
}
The name field in the local file header section remains unchanged, so there will be a mismatch exception in this library.
It's tricky but maybe problematic, I don't know..

How to create a text file inside a specific directory?

I am trying to cretae a file SYS_CONFIG_FILE_NAME inside a specific directory SYS_CONFIG_DIR_NAME. using the below posted code, when i run the java program it creates two directories instead of one directory and one text file inside that directory.
The out put of the below code is
SYS_CONFIG/config.txt. But `config.txt` is not a text file it is just a directory named `config.txt`
i referred also to some question in stackoverflow but i could not find a solution. Please let me know what I am missing?
code:
private final static String SYS_CONFIG_DIR_NAME = "SYS_CONFIG";
private final static String SYS_CONFIG_FILE_NAME = "config.txt";
private static File newSysConfigInstance() throws IOException {
// TODO Auto-generated method stub
File f = new File(SYS_CONFIG_FILE_PATH + "/" + SYS_CONFIG_DIR_NAME + "/" + SYS_CONFIG_FILE_NAME);
f.mkdirs();
f.createNewFile();
return f;
}
I would do it that way, you have always to call createNewFile() to create a new instance of the file if it is not created.
File dir = new File(SYS_CONFIG_FILE_PATH, SYS_CONFIG_DIR_NAME);
f.mkdirs(); // this to create the directories need for your path.
File file = new File(dir, SYS_CONFIG_FILE_NAME);
if (file.createNewFile()) {
system.out.prinln("file first created");
}else {
// print a message here
}
return file;
You are telling it to make a directory of the form a/b/c if you want a directory of the form a/b then you should give it the directory you want it to create.
File dir = new File(SYS_CONFIG_FILE_PATH, SYS_CONFIG_DIR_NAME);
f.mkdirs();
return new File(dir, SYS_CONFIG_FILE_NAME);
You don't have to pre-create files before you use them.

Locate a specific file in a directory by name plus saving a file to the local folder

I would like to locate a file named SAVE.properties. I have looked at different questions that seem like they would answer me, but I can't see that they do.
For example, I would like to check to see whether or not SAVE.properties exists within a directory (and its subfolders).
I would also like to know how I could save a .properties file (and then read it afterwards from this location) to the directory where my program is being run from. If it is run from the desktop, it should save the .properties file there.
Saving properties can easily be achieved through the use of Properties#store(OutputStream, String), this allows you to define where the contents is saved to through the use of an OutputStream.
So you could use...
Properties properties = ...;
//...
try (FileOutputStream os = new FileOutputStream(new File("SAVE.properties"))) {
properties.store(os, "Save");
} catch (IOException exp) {
exp.printStackTrace();
}
You can also use Properties#load(InputStream) to read the contents of a "properties" file.
Take a closer look at Basic I/O for more details.
Locating a File is as simple as using
File file = new File("SAVE.properties");
if (file.exists) {...
This checks the current working directory for the existence of the specified file.
Searching the sub directories is little more involved and will require you to use some recursion, for example...
public File find(File path) {
File save = new File(path, "SAVE.properties");
if (!save.exists()) {
save = null;
File[] dirs = path.listFiles(new FileFilter() {
#Override
public boolean accept(File pathname) {
return pathname.isDirectory();
}
});
for (File dir : dirs) {
save = find(dir);
if (save != null) {
break;
}
}
}
return save;
}
Using find(new File(".")) will start searching from the current working directory. Just beware, under the right circumstances, this could search your entire hard disk.

Is it possible to create a NEW zip file using the java FileSystem?

I've successfully modified the contents of a (existing) zip file using the FileSystem provided by java 7, but when I tried to create a NEW zip file by this method it fails, with the error message that says: "zip END header not found", it is logical because of the way I'm doing it, first I create the file (Files.createFile) which is a completely empty file, and then I try to access to its file system , and since the file is empty its impossible to find any header inside the zip, my question is is there any way to create a new zip file completely empty using this method?; the hack that I've considered is adding an empty new ZipEntry to a the zip file and then using that new empty file to crate the file system based on it, but i really want to think that the guys of oracle implemented a better (easier) way to do this with nio and the filesystems...
this is my code (the error appears when creating the file system):
if (!zipLocation.toFile().exists()) {
if (creatingFile) {
Files.createFile(zipLocation);
}else {
return false;
}
} else if (zipLocation.toFile().exists() && !replacing) {
return false;
}
final FileSystem fs = FileSystems.newFileSystem(zipLocation, null);
.
.
.
zipLocation is a Path
creatingFile is a boolean
ANSWER:
in my particular case the answer given didn't work appropriately because of the spaces in the path, therefore i have to do it the way i didn't want to:
Files.createFile(zipLocation);
ZipOutputStream out = new ZipOutputStream(
new FileOutputStream(zipLocation.toFile()));
out.putNextEntry(new ZipEntry(""));
out.closeEntry();
out.close();
it does not mean that the given answer is wrong, it just didn't work for my particular case
As described in The Oracle Site:
public static void createZip(Path zipLocation, Path toBeAdded, String internalPath) throws Throwable {
Map<String, String> env = new HashMap<String, String>();
// check if file exists
env.put("create", String.valueOf(Files.notExists(zipLocation)));
// use a Zip filesystem URI
URI fileUri = zipLocation.toUri(); // here
URI zipUri = new URI("jar:" + fileUri.getScheme(), fileUri.getPath(), null);
System.out.println(zipUri);
// URI uri = URI.create("jar:file:"+zipLocation); // here creates the
// zip
// try with resource
try (FileSystem zipfs = FileSystems.newFileSystem(zipUri, env)) {
// Create internal path in the zipfs
Path internalTargetPath = zipfs.getPath(internalPath);
// Create parent directory
Files.createDirectories(internalTargetPath.getParent());
// copy a file into the zip file
Files.copy(toBeAdded, internalTargetPath, StandardCopyOption.REPLACE_EXISTING);
}
}
public static void main(String[] args) throws Throwable {
Path zipLocation = FileSystems.getDefault().getPath("a.zip").toAbsolutePath();
Path toBeAdded = FileSystems.getDefault().getPath("a.txt").toAbsolutePath();
createZip(zipLocation, toBeAdded, "aa/aa.txt");
}

How to create a directory in Java?

How do I create Directory/folder?
Once I have tested System.getProperty("user.home");
I have to create a directory (directory name "new folder" ) if and only if new folder does not exist.
new File("/path/directory").mkdirs();
Here "directory" is the name of the directory you want to create/exist.
After ~7 year, I will update it to better approach which is suggested by Bozho.
File theDir = new File("/path/directory");
if (!theDir.exists()){
theDir.mkdirs();
}
With Java 7, you can use Files.createDirectories().
For instance:
Files.createDirectories(Paths.get("/path/to/directory"));
You can try FileUtils#forceMkdir
FileUtils.forceMkdir("/path/directory");
This library have a lot of useful functions.
mkdir vs mkdirs
If you want to create a single directory use mkdir
new File("/path/directory").mkdir();
If you want to create a hierarchy of folder structure use mkdirs
new File("/path/directory").mkdirs();
Create a single directory.
new File("C:\\Directory1").mkdir();
Create a directory named “Directory2 and all its sub-directories “Sub2″ and “Sub-Sub2″ together.
new File("C:\\Directory2\\Sub2\\Sub-Sub2").mkdirs()
Source: this perfect tutorial , you find also an example of use.
For java 7 and up:
Path path = Paths.get("/your/path/string");
Files.createDirectories(path);
It seems unnecessary to check for existence of the dir or file before creating, from createDirectories javadocs:
Creates a directory by creating all nonexistent parent directories first. Unlike the createDirectory method, an exception is not thrown if the directory could not be created because it already exists.
The attrs parameter is optional file-attributes to set atomically when creating the nonexistent directories. Each file attribute is identified by its name. If more than one attribute of the same name is included in the array then all but the last occurrence is ignored.
If this method fails, then it may do so after creating some, but not all, of the parent directories.
The following method should do what you want, just make sure you are checking the return value of mkdir() / mkdirs()
private void createUserDir(final String dirName) throws IOException {
final File homeDir = new File(System.getProperty("user.home"));
final File dir = new File(homeDir, dirName);
if (!dir.exists() && !dir.mkdirs()) {
throw new IOException("Unable to create " + dir.getAbsolutePath();
}
}
Neat and clean:
import java.io.File;
public class RevCreateDirectory {
public void revCreateDirectory() {
//To create single directory/folder
File file = new File("D:\\Directory1");
if (!file.exists()) {
if (file.mkdir()) {
System.out.println("Directory is created!");
} else {
System.out.println("Failed to create directory!");
}
}
//To create multiple directories/folders
File files = new File("D:\\Directory2\\Sub2\\Sub-Sub2");
if (!files.exists()) {
if (files.mkdirs()) {
System.out.println("Multiple directories are created!");
} else {
System.out.println("Failed to create multiple directories!");
}
}
}
}
Though this question has been answered. I would like to put something extra, i.e.
if there is a file exist with the directory name that you are trying to create than it should prompt an error. For future visitors.
public static void makeDir()
{
File directory = new File(" dirname ");
if (directory.exists() && directory.isFile())
{
System.out.println("The dir with name could not be" +
" created as it is a normal file");
}
else
{
try
{
if (!directory.exists())
{
directory.mkdir();
}
String username = System.getProperty("user.name");
String filename = " path/" + username + ".txt"; //extension if you need one
}
catch (IOException e)
{
System.out.println("prompt for error");
}
}
}
Just wanted to point out to everyone calling File.mkdir() or File.mkdirs() to be careful the File object is a directory and not a file. For example if you call mkdirs() for the path /dir1/dir2/file.txt, it will create a folder with the name file.txt which is probably not what you wanted. If you are creating a new file and also want to automatically create parent folders you can do something like this:
File file = new File(filePath);
if (file.getParentFile() != null) {
file.getParentFile().mkdirs();
}
This the way work for me do one single directory or more or them:
need to import java.io.File;
/*enter the code below to add a diectory dir1 or check if exist dir1, if does not, so create it and same with dir2 and dir3 */
File filed = new File("C:\\dir1");
if(!filed.exists()){ if(filed.mkdir()){ System.out.println("directory is created"); }} else{ System.out.println("directory exist"); }
File filel = new File("C:\\dir1\\dir2");
if(!filel.exists()){ if(filel.mkdir()){ System.out.println("directory is created"); }} else{ System.out.println("directory exist"); }
File filet = new File("C:\\dir1\\dir2\\dir3");
if(!filet.exists()){ if(filet.mkdir()){ System.out.println("directory is created"); }} else{ System.out.println("directory exist"); }
if you want to be sure its created then this:
final String path = "target/logs/";
final File logsDir = new File(path);
final boolean logsDirCreated = logsDir.mkdir();
if (!logsDirCreated) {
final boolean logsDirExists = logsDir.exists();
assertThat(logsDirExists).isTrue();
}
beacuse mkDir() returns a boolean, and findbugs will cry for it if you dont use the variable. Also its not nice...
mkDir() returns only true if mkDir() creates it.
If the dir exists, it returns false, so to verify the dir you created, only call exists() if mkDir() return false.
assertThat() will checks the result and fails if exists() returns false. ofc you can use other things to handle the uncreated directory.
This function allows you to create a directory on the user home directory.
private static void createDirectory(final String directoryName) {
final File homeDirectory = new File(System.getProperty("user.home"));
final File newDirectory = new File(homeDirectory, directoryName);
if(!newDirectory.exists()) {
boolean result = newDirectory.mkdir();
if(result) {
System.out.println("The directory is created !");
}
} else {
System.out.println("The directory already exist");
}
}
Here is one attractiveness of the java, using Short Circuit OR '||', testing of the directory's existence along with making the directory for you
public File checkAndMakeTheDirectory() {
File theDirectory = new File("/path/directory");
if (theDirectory.exists() || theDirectory.mkdirs())
System.out.println("The folder has been created or has been already there");
return theDirectory;
}
if the first part of the if is true it does not run the second part and if the first part is false it runs the second part as well
public class Test1 {
public static void main(String[] args)
{
String path = System.getProperty("user.home");
File dir=new File(path+"/new folder");
if(dir.exists()){
System.out.println("A folder with name 'new folder' is already exist in the path "+path);
}else{
dir.mkdir();
}
}
}

Categories