I have a folder in which there is a .dat file and one is .zip file ,I have to move the .zip file to another directory
I have two folders one is
1) c:\source folder --> having two files abc.dat and other is abc.zip
2) c:\destination ---> in which zip shpould be get copied
please advise how to achiev this what I have done rite now is ...
File directory = new File(sourceFolder);
File[] listFiles = (mcrpFilePath).listFiles();
for (File f : listFiles) {
if (f.isFile()) { // ?? here logic to pick up the zip file
//logic to move the zip file to other directory
}
}
Use File.renameTo
Renames the file denoted by this abstract pathname.
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.
Here is Example
Or you can use Files#move (if you are using java 7)
Move or rename a file to a target file.
here is Example using move()
As simple as using the method renameTo() in File class.
public boolean renameTo(File dest);
Renames the file denoted by this abstract pathname.
Get file full path and rename it to the required location.
And make use of boolean that return by that method,to know weather it's successfully moved or not.
For detecting your zip-file:
if(f.getName.equals("abc.zip"))
or for all zip files:
if(f.getName.endsWith(".zip"))
With a regex:
if(f.getName.matches("abc*\\.zip"))
For moving it:
f.renameTo(new File("C:\dest\abc.zip");
Or, more simply:
new File("C:\src\abc.zip").renameTo("C:\dest\abc.zip");
catching exceptions as needed.
Use java.io.File and its methods to get the list of .zip files and move them (Tutorial - Moving a File or Directory).
import static java.nio.file.StandardCopyOption.*;
...
Files.move(source, target, REPLACE_EXISTING);
SOURCE
Related
I want to be able to iterate through a package of files as if the package were a folder.
Something like the below (scripts being the java package):
File scriptFolder = new File("scripts").getAbsoluteFile();
The packages appear are not being treated like folders. If I hardcode the path C:\Users\...\project_folder\...\scripts the File.isFile() method returns false for the package. If I do new File (C:\Users\...\project_folder\...\scripts\script).isFile() I get true.
I want to get a File of the folder so I can get a list of the files in the folder and iterate through it.
The .isFile() method returns true only if you are referencing a plain jane normal file. If you're referencing a directory, it'd return false. Try .isDirectory() or possibly .exists().
Or don't; there's no real need:
File[] filesInDir = new File("C:\\Users\\....\\scripts").listFiles();
if (filesInDir == null) {
// this means it wasn't a directory or didn't exist or isn't readable
} else {
for (File child : filesInDir) {
// called for each file in dir
}
}
The official javadocs say this about File#isFile():
Tests whether the file denoted by this abstract pathname is a normal file. A file is normal if it is not a directory and, in addition, satisfies other system-dependent criteria. Any non-directory file created by a Java application is guaranteed to be a normal file.
You can check if it is a directory with File#isDirectory(), then if it is, you can list its contents with File#listFiles().
Unless I'm missing something in your question C:\Users...\project_folder...\scripts is a directory so isFile() will return false because it is not a file.
I am currently programming a file name normaliser. Files have a format and folders dont. When I rename a file I need to make sure that I do not affect the format therefore I did
fileName.substring(fileName.lastIndexOf("."),fileName.length)
thereby if I want to replace all the periods in a fileName it does not affect the format, when a folder with periods in its name goes through this process, the last instance of the period is still part of its name, therefore it does not replace all the dots in the folders name. I need to know how to distinguish between a file and a folder so I can fix this.
You can use
someFile.isDirectory();
It returns true if the file is a folder, and false if not.
You can use File.isDirectory() to test whether the file denoted by this abstract pathname is a directory. You can also use File.isFile() to test whether the file denoted by this abstract pathname is a normal file. A file is normal if it is not a directory and, in addition, satisfies other system-dependent criteria.
File f = new File(fileName);
if (f.isFile()) {
// it's a file.
} else if (f.isDirectory()) {
// it's a directory.
}
Hello one of the parts of a program i'm working on requires the ability to search through a directory. I understand how using a path variable works and how to get to a directory; but once you are in the directory how can you distinguish files from one another? Can we make an array/or a linked list of the files contained within the directory and search using that?
In this specific program the goal is for the user to input a directory, from there go into sub-directory and find a file that ends with .mp3 and copy that to a new user created directory. It is certain that there will only be one .mp3 file in the folder.
Any help would be very much appreciated.
Seeing what you say, I will suppose that you use the java7 Path api.
To know if a path is a directory or a simple file, use Files.isDirectory(Path)
To list the files / directories in your directory, use Files.list(Path)
The javadoc of the Files class : http://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html
If you use the "old" java.io.File api, then you have a listFiles method, which can take a FileFilter as argument to filter, for exemple, only the files ending with ".mp3".
Good luck
Get Files as so:
List<String> results = new ArrayList<String>();
File[] files = new File("/path/to/the/directory").listFiles();
for (File file : files)
if (file.isFile())
results.add(file.getName());
If you want the extension:
public static String getExtension(String filename){
String extension = "";
int i = fileName.lastIndexOf('.');
if (i > 0)
extension = fileName.substring(i+1);
return extension;
}
There are other ways to get file extensions listed here but they usually require a common external library.
You can use the File object to represent your directory, and then use the listFiles() (which return an array of files File[]) to retrieve the files into that directory.
If you need to search through subdirectories, you can use listFiles() recursively for each directory you encounter.
As for the file extension, the Apache Commons IO library has a neat FileFilter for that: the SuffixFileFilter.
A program we have erred when trying to move files from one directory to another. After much debugging I located the error by writing a small utility program that just moves a file from one directory to another (code below). It turns out that while moving files around on the local filesystem works fine, trying to move a file to another filesystem fails.
Why is this? The question might be platform specific - we are running Linux on ext3, if that matters.
And the second question; should I have been using something else than the renameTo() method of the File class? It seems as if this just works on local filesystems.
Tests (run as root):
touch /tmp/test/afile
java FileMover /tmp/test/afile /root/
The file move was successful
touch /tmp/test/afile
java FileMover /tmp/test/afile /some_other_disk/
The file move was erroneous
Code:
import java.io.File;
public class FileMover {
public static void main(String arguments[] ) throws Exception {
boolean success;
File file = new File(arguments[0]);
File destinationDir = new File(arguments[1]);
File destinationFile = new File(destinationDir,file.getName() );
success = file.renameTo(destinationFile);
System.out.println("The file move was " + (success?"successful":"erroneous"));
}
}
Java 7 and above
Use Files.move(Path source, Path target, CopyOption... opts).
Note that you must not provide the ATOMIC_MOVE option when moving files between file systems.
Java 6 and below
From the docs of File.renameTo:
[...] The rename operation might not be able to move a file from one filesystem to another [...]
The obvious workaround would be to copy the file "manually" by opening a new file, write the content to the file, and delete the old file.
You could also try the FileUtils.moveFile method from Apache Commons.
Javadoc to the rescue:
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.
Note that the Files class defines the move method to move or rename a
file in a platform independent manner.
From the docs:
Renames the file denoted by this abstract pathname.
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.
If you want to move file between different file system you can use Apache's moveFile
your ider is error
beause /some_other_disk/ is relative url but completely url ,can not find the url
i have example
java FileMover D:\Eclipse33_workspace_j2ee\test\src\a\a.txt D:\Eclipse33_workspace_j2ee\test\src
The file move was successful
java FileMover D:\Eclipse33_workspace_j2ee\test\src\a\a.txt \Eclipse33_workspace_j2ee\test\src
The file move was erronous
result is url is error
The code I am running is in /Test1/Example. If I need to read a .txt file in /Test1 how do I get Java to go back 1 level in the directory tree, and then read my .txt file
I have searched/googled and have not been able to find a way to read files in a different location.
I am running a java script in an .htm file located at /Test1/Test2/testing.htm. Where it says script src=" ". What would I put in the quotations to have it read from my file located at /Test1/example.txt.
In Java you can use getParentFile() to traverse up the tree. So you started your program in /Test1/Example directory. And you want to write your new file as /Test1/Example.txt
File currentDir = new File(".");
File parentDir = currentDir.getParentFile();
File newFile = new File(parentDir,"Example.txt");;
Obviously there are multiple ways to do this.
You should be able to use the parent directory reference of "../"
You may need to do checks on the OS to determine which directory separation you should be using ['\' compared to '/']
When you create a File object in Java, you can give it a pathname. You can either use an absolute pathname or a relative one. Using absolutes to do what you want would require:
File file = new File("/Test1/myFile.txt");
if(file.canRead())
{
// read file here
}
Using relatives paths if you want to run from the location /Test1/Example:
File file = new File("../myFile.txt");
if(file.canRead())
{
// read file here
}
I had a similar experience.
My requirement is: I have a file named "sample.json" under a directory "input", I have my java file named "JsonRead.java" under a directory "testcase". So, the entire folder structure will be like untitled/splunkAutomation/src and under this I have folders input, testcase.
once after you compile your program, you can see a input file copy named "sample.json" under a folder named "out/production/yourparentfolderabovesrc/input" and class file named "JsonRead.class" under a folder named "out/production/yourparentfolderabovesrc/testcase". So, during run time, Java will actually refer these files and NOT our actual .java file under "src".
So, my JsonRead.java looked like this,
package testcase;
import java.io.*;
import org.json.simple.JSONObject;
public class JsonRead{
public static void main(String[] args){
java.net.URL fileURL=JsonRead.class.getClass().getResource("/input/sample.json");
System.out.println("fileURL: "+fileURL);
File f = new File(fileURL.toURI());
System.out.println("fileIs: "+f);
}
}
This will give you the output like,
fileURL: file:/C:/Users/asanthal/untitled/out/production/splunkAutomation/input/sample.json
fileIs: C:\Users\asanthal\untitled\out\production\splunkAutomation\input\sample.json
It worked for me. I was saving all my classes on a folder but I needed to read an input file from the parent directory of my classes folder. This did the job.
String FileName = "Example.txt";
File parentDir = new File(".."); // New file (parent file ..)
File newFile = new File(parentDir,fileName); //open the file