Move all files from folder to other folder with java [duplicate] - java

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Copying files from one directory to another in Java
How can I move all files from one folder to other folder with java?
I'm using this code:
import java.io.File;
public class Vlad {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
// File (or directory) to be moved
File file = new File("C:\\Users\\i074924\\Desktop\\Test\\vlad.txt");
// Destination directory
File dir = new File("C:\\Users\\i074924\\Desktop\\Test2");
// Move file to new directory
boolean success = file.renameTo(new File(dir, file.getName()));
if (!success) {
System.out.print("not good");
}
}
}
but it is working only for one specific file.
thanks!!!

By using org.apache.commons.io.FileUtils class
moveDirectory(File srcDir, File destDir) we can move whole directory

If a File object points to a folder you can iterate over it's content
File dir1 = new File("C:\\Users\\i074924\\Desktop\\Test");
if(dir1.isDirectory()) {
File[] content = dir1.listFiles();
for(int i = 0; i < content.length; i++) {
//move content[i]
}
}

Since Java 1.7 there is java.nio.file.Files which offers operations to work with files and directories. Especially the move, copy and walkFileTree functions might be of interest to you.

You can rename the directory itself.
You can iterate over files in directory and rename them one-by-one. If directory can contain subdirectories you have to do this recursively.
you can use utility like Apache FileUtils that already does all this.

Related

New file inside a directory using java

I want to determine if a new file or document is placed inside a specific folder/directory using java. For example, There are no files inside the "C:\Users\User\Documents" directory and then I downloaded a pdf file from the Internet and was placed on the mentioned directory. How can I determine if a new file is detected on the directory using java programming language? (It should also print-out the name of the directory and the new file name). Can I have any tips on how to create this kind of program using Java language? It should be continuous or in an infinite loop.
I tried this by using this:
package readfilesfromfolder;
import java.io.File;
public class ReadFilesFromFolder {
public static File folder = new File("C:/Documents and Settings/My Documents/Downloads");
static String temp = "";
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Reading files under the folder "+ folder.getAbsolutePath());
listFilesForFolder(folder);
}
public static void listFilesForFolder(final File folder) {
for (final File fileEntry : folder.listFiles()) {
if (fileEntry.isDirectory()) {
listFilesForFolder(fileEntry);
} else {
if (fileEntry.isFile()) {
temp = fileEntry.getName();
if ((temp.substring(temp.lastIndexOf('.') + 1, temp.length()).toLowerCase()).equals("txt"))
System.out.println("File= " + folder.getAbsolutePath()+ "\\" + fileEntry.getName());
}
}
}
}
}
But based on the outcome, it just accessed the directory but did not list for any new items. Also, it is not yet in loop because I haven't placed it yet. Thank you :) (*Note: I am still new to Java programming :) *)
You could use the Watch Service. A watch service that watches registered objects for changes and events. For example a file manager may use a watch service to monitor a directory for changes so that it can update its display of the list of files when files are created or deleted.
A good example can be found here.
You too can use the Commons IO library from the Apache Foundation, mainly the org.apache.commons.io.monitor package.
Thank you guys for the tip! :) I found out how to do this using the WatchService :)
This is the output based on my research and reading :)
public static void main(String[] args) throws IOException{
// TODO code application logic here
WatchService watchService = FileSystems.getDefault().newWatchService();
//The path needed for changes
Path directory = Paths.get("C:\\Users\\User\\Documents");
//To determine whether a file is created, deleted or modified
//ENTRY_CREATE can be changed to ENTRY_MODIFY and ENTRY_DELETE
WatchKey watchKey = directory.register(watchService, StandardWatchEventKinds.ENTRY_CREATE);
//This portion is for the output of what file is created, modified, or deleted
while (true){
for (WatchEvent<?> event : watchKey.pollEvents()) {
System.out.println(event.kind());
Path file = directory.resolve((Path) event.context());
System.out.println(file);
}
}
}
Hope this can help other people. Thanks also to those who helped me as well as to the authors of different research materials used to create this one :) Credits to Mr.Kriechel for this one :)

how to get list of files from directory using java [duplicate]

This question already has answers here:
in java how to get files in a given directory
(2 answers)
Closed 8 years ago.
I want to get the list of java files in a folder.
For example, i will provide the input as "c:\main\java"
Inside java, there will be package structure like "c:\maina\java\io\ci\", where java files will be present in ci folder.
now i want to write code to list those java files from the folder.
use Apache Fileutils listFiles method
public static Collection<File> listFiles(File directory,
String[] extensions,
boolean recursive)
and pass the extension string array values as java
Try this:
String path = "your file path";
String files;
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++)
{
if (listOfFiles[i].isFile())
{
files = listOfFiles[i].getName();
System.out.println(files);
}
}

How to loop through all the files in a folder (if the names of the files are unknown)? [duplicate]

This question already has answers here:
how to read directories in java
(4 answers)
list all files from directories and subdirectories in Java
(6 answers)
Closed 9 years ago.
There is a folder: C:\\Users\..myfolder
It contains .pdf files (or any other, say .csv). I cannot change the names of those files, and I do not know the number of those files. I need to loop all of the files one by one.
How can I do this?
(I know how to do this if I knew the names)
Just use File.listFiles
final File file = new File("whatever");
for(final File child : file.listFiles()) {
//do stuff
}
You can use the FileNameExtensionFilter to filter your files too
final FileNameExtensionFilter extensionFilter = new FileNameExtensionFilter("N/A", "pdf", "csv"//, whatever other extensions you want);
final File file = new File("whatever");
for (final File child : file.listFiles()) {
if(extensionFilter.accept(child)) {
//do stuff
}
}
Annoyingly FileNameExtensionFilter comes from the javax.swing package so cannot be used directly in the listFiles() api, it is still more convenient than implementing a file extension filter yourself.
File.listFiles() gives you an array of files in a folder. You can then split the filenames to get the extension and check if it is .pdf.
File[] files = new File("C:\\Users\..myfolder").listFiles();
for (File file : files) {
if (!file.isFile()) continue;
String[] bits = file.getName().split(".");
if (bits.length > 0 && bits[bits.length - 1].equalsIgnoreCase("pdf")) {
// Do stuff with the file
}
}
So you can have more options, try the Java 7 NIO way of doing this
public static void main(String[] args) throws Exception {
try (DirectoryStream<Path> files = Files.newDirectoryStream(Paths.get("/"))) {
for (Path path : files) {
System.out.println(path.toString());
}
}
}
You can also provide a filter for the paths in the form of a DirectoryStream.Filter implementation
public static void main(String[] args) throws Exception {
try (DirectoryStream<Path> files = Files.newDirectoryStream(Paths.get("/"),
new DirectoryStream.Filter<Path>() {
#Override
public boolean accept(Path entry) throws IOException {
return true; // or whatever you want
}
})
) {
for (Path path : files) {
System.out.println(path.toString());
}
}
}
Obviously you can extract the anonymous class to an actual class declaration.
Note that this solution cannot return null like the listFiles() solution.
For a recursive solution, check out the FileVisitor interface. For path matching, use the PathMatcher interface along with FileSystems and FileSystem. There are examples floating around Stackoverflow.
You can use Java.io.File.listFiles() method to get a list of all files and folders inside a folder.

Loading files from java jar file [duplicate]

This question already has answers here:
Get resource from jar
(4 answers)
Closed 9 years ago.
Hi I am stuck with following code. I would like to get files from folder but when I export project to jar file it wont work any idea?
public String getXSDfilenames() {
String filenames= "";
try {
File currDir = new File(".");
String path = currDir.getAbsolutePath();
path = path.substring(0, path.length()-1);
File file = new File(path+"src\\schemaFiles");
String[] files = file.list(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(".xsd");
}
});
if (file.exists()) {
for (int i = 0; i < files.length; i++) {
System.out.println(path+"src\\schemaFiles\\"+files[i]);
filenames = filenames + files[i] + newline;
}
} else {
System.out.println("No schema files founded in default folder!");
}
}
catch (Throwable e1) {
System.out.println(e1);
}
return filenames;
}
}
If you change the name of your XXX.jar file to XXX.zip, then open it in whatever Zip file utility you might have available, you can look inside the file and see 1. Whether your files are getting included in the jar at all, and if they are, 2. the actual path in which they are stored. I strongly suspect there's now src folder inside your jar.
Also, if you're NOT expecting the files to be in the jar, then you'll probably need to supply an absolute path to the files.
If they are in the jar, then check out these questions:
load file within a jar,
How to use ClassLoader.getResources() correctly?,
How do I list the files inside a JAR file?

Show issue while deleting directory [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Delete a folder on SD card
In my app i saved all my data using internal storage i.e file. So at the first instance by using the ContextWrapper cw = new ContextWrapper(getApplicationContext()); class i get the directory path as m_AllPageDirectoryPath = cw.getDir("AllPageFolder", Context.MODE_PRIVATE); Inside this directory path i saved some file File as Page01, page02, Page03 and so on.
Again inside Page01 i saved some file like image01, image02...using the same concept m_PageDirectoryPath = cw.getDir("Page01", Context.MODE_PRIVATE); Now on delete of m_AllPageDirectoryPath i want to delete all the file associate with it. I tried using this code but it doesn't work.
File file = new File(m_AllPageDirectoryPath.getPath());
file.delete();
Your code only works if your directory is empty.
If your directory includes Files and Sub Directories, then you have to delete all files recursively..
Try this code,
// Deletes all files and subdirectories under dir.
// Returns true if all deletions were successful.
// If a deletion fails, the method stops attempting to delete and returns false.
public static boolean deleteDir(File dir) {
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i=0; i<children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
// The directory is now empty so delete it
return dir.delete();
}
(Actually you have to search on internet before asking like this questions)

Categories