Hi i'm working on a simple program and for the set up of the program i need the program to check a directory for zip files and any zip files in there need to be moved into another folder.
Lets say i have folder1 and it contains 6 zip files and then i have another folder called folder2 that i need all the zips and only the zips in folder1 moved to folder2
Thank you for any help one this problem.
Btw i'm a noob so any code samples would be greatly appreciated
For each file in folder1, use String#endsWith() to see if the file name ends with ".zip". If it does, move it to folder2. FilenameFilter provides a nice way to do this (though it's not strictly necessary).
It would look something like this (not tested):
File f1 = new File("/path/to/folder1");
File f2 = new File("/path/to/folder2");
FilenameFilter filter = new FilenameFilter()
{
#Override public boolean accept(File dir, String name)
{
return name.endsWith(".zip");
}
};
for (File f : f1.listFiles(filter))
{
// TODO move to folder2
}
The pattern of matching "*.zip" in a filesystem is called "file globbing." You can easily select all of these files with a ".zip" file glob using this documentation:
Finding Files. java.nio.file.PathMatcher is what you want. Alternatively, you can list directories as normal and use the name of the file and the ".endsWith()" method of String which will do something similar.
Use a FilenameFilter
String pathToDir = "/some/directory/path";
File myDir = new File(pathToDir);
File[] zipFiles = myDir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(".zip")
}
});
List all file in baseDir, if it ends with '.zip' moves it to destDir
// baseDir = folder1
// destDir = folder2
File[] files = baseDir.listFiles();
for (int i=0; i<files.length; i++){
if (files[i].endsWith(".zip")){
files[i].renameTo(new File(destDir, files[i].getName()));
}
}
API of renameTo
My solution:
import java.io.*;
import javax.swing.*;
public class MovingFile
{
public static void copyStreamToFile() throws IOException
{
FileOutputStream foutOutput = null;
String oldDir = "F:/CAF_UPLOAD_04052011.TXT.zip";
System.out.println(oldDir);
String newDir = "F:/New/CAF_UPLOAD_04052011.TXT.zip.zip"; // name the file in destination
File f = new File(oldDir);
f.renameTo(new File(newDir));
}
public static void main(String[] args) throws IOException
{
copyStreamToFile();
}
}
Related
I need to read an xml-file that has as dynamic name. File name is something like "1234_employees.xml" in which the digits change daily. There is only one .xml in the folder.
Doesn't regex this work for files/paths?
Something like:
File myxml = new File("*employees.xml");
You can use WildcardFileFilter:
File dir = new File(".");
FileFilter fileFilter = new WildcardFileFilter("*employees.xml");
File employeesXml = dir.listFiles(fileFilter)[0];
You will need to install this library:
https://mvnrepository.com/artifact/org.apache.commons/commons-io/1.3.2
You can use a FilenameFilter as below
for (File inputFile : yourDirectory.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith("employees.xml");
}
})) {
// process inputFile here
}
I would like to read a file from a directory. In this directory there are eight additional files with the same extension (.csv). Likewise, the file name is not directly known.
The name of the file looks like this:
test_file_1_2017_06_24.csv
It can change however, if I call the directory the next day . Then the file name is:
test_file_2_2017_06_25.csv or test_file_1_2017_06_25.
The name of the file and the date change.
Is there a way to read the file "variable" in Java or to read the file but donĀ“t know the exactly name? The directory is always the same ("H:/) (After the file read, then the file respectively the resulting string is furtherprocessed with split() ).
Thanks for helpfull answers!
Edit: Read the directory and shows only csv-Files
File dir = new File("H:/");
File[] fileArray = dir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(".csv");
}
});
for(File f: fileArray){
System.out.println(f.getName());
}
File directory = new File("H:/");
File[] allFilesInDir = directory.listFiles();
See https://docs.oracle.com/javase/7/docs/api/java/io/File.html#listFiles().
You can also provide a FilenameFilter to get only .csv files:
File[] allCsvFiles = directory.listFiles( new FilenameFilter() {
public boolean accept(File dir, String name) {
if ( name.toUpperCase().endsWith(".CSV") ) {
return new File(dir,name).isFile(); // Make sure we don't accept sub-directories ending in .csv
}
}
});
You can use the following code to go through a folder, check for csv files and work with it. Hope it helps.
File folder = new File("H:/"); /*path to your folder*/
String[] filesPresent = folder.list();
if(filesPresent.length==0){
System.out.println("Nothing to delete");
}else{
for(String fileName : filesPresent){ // looping through files in the directory
if(fileName.toLowerCase().endsWith(".csv") && (new File(fileName).isFile())){
//this is a csv file.
//you can do your operations here
File file = new File(fileName);
//now you can do any file operations required with the file object
}
}
}
I try to make a java code that will search for every directory that is starting with "test-" and then will copy files to it.
Currently i have this as code
File dir = new File("C:\\Users\\test\\Desktop\\test");
File[] foundFiles = dir.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.startsWith("test-");
But, i can't figure out how to let it now copy files to the directories with that as prefix..
You would probably want to do something like:
for(File cpy:listOfFilesToCopy){
for(File dir:foundFiles){
Files.copy(cpy,dir);
}
}
Is it possible to read single type of file (say like CSV or txt) from the directory containing multiple file types (say like cvs , txt , doc, xml, html, etc..)
My problem is I have to provide path of the mainDirectory as an input , which further has layers of subdirectories inside it. I specifically need to read and process CSV files within these directories as I further dive in.
I am done with multiple layers of folder traversing using recursion courtesy which I have the names and total count of the files within the mainDirectory. I am also done with logic to read and CSV files. All I need to do is to get path only of CSV files and process them.
i am using below mentioned code for traversing multiple folders and getting the name :-
package org.ashu.input;
import java.io.File;
/**
*
* #author ashutosh
*/
public class MultiDir {
private int fileCount;
public void readFile(File f){
System.out.println(f.getPath());
fileCount++;
}
public void readDir(File f){
File subdir[] = f.listFiles();
for(File f_arr : subdir){
if(f_arr.isFile()){
this.readFile(f_arr);
}
if(f_arr.isDirectory()){
this.readDir(f_arr);
}
}
}
public static void main(String[] args){
MultiDir md = new MultiDir();
File mainDir = new File("/Users/ashutosh/Downloads/main_directory");
md.readDir(mainDir);
System.out.println(md.fileCount);//all file count = 1576, need to specifically get CSV
}
}
Any suggestion please.
This code will return every file matching the given extension (in your case .csv):
public static List<File> getFiles(String extension, final File folder)
{
extension = extension.toUpperCase();
final List<File> files = new ArrayList<File>();
for (final File file : folder.listFiles())
{
if (file.isDirectory())
files.addAll(getFiles(extension, file));
else if (file.getName().toUpperCase().endsWith(extension))
files.add(file);
}
return files;
}
You can simply check the extension of the file in your readDir() method. The below looks for jpg, you can use your desired extension
public void readDir(File f){
File subdir[] = f.listFiles();
for(File f_arr : subdir){
if(f_arr.isFile() && f_arr.getName().endsWith(".jpg")){
this.readFile(f_arr);
}
if(f_arr.isDirectory()){
this.readDir(f_arr);
}
}
}
I need to get the paths of files and their parent directories in java from a given directory but not including it.
So for example, If my method was given the path: /home/user/test as a path it would return the paths of all files in that directory and under it.
So if /home/user/test had the sub folders: /subdir1 and /subdir2 each containing file1.txt and file2.txt then the result of the method would be 2 strings containing /subdir1/file1.txt and /subdir2/file2.txt
And if subdir1 had a directory inside it called subsubdir and inside that file3.txt, then the string created for that file would be /subdir1/subsubdir/file3.txt, and if there are further sub directories that would continue.
The idea is I just want the directory paths above the file but not the absolute path so only the directories AFTER the initial given path.
I know its a little confusing but I'm sure someone can make sense of it. Right now all I have is a recursive function that prints out file names and their absolute paths.
Any assistance on this?
What would have been nice if you had tried something and asked questions about that...
However...
public class TestFileSearch {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
new TestFileSearch();
}
public TestFileSearch() {
File parentPath = new File("C:/Users/shane/Documents");
List<String> files = list(parentPath);
for (String file : files) {
System.out.println(file);
}
}
protected List<String> list(File parent) {
return listFiles(parent, parent);
}
protected List<String> listFiles(File parent, File folder) {
List<String> lstFiles = new ArrayList<String>(25);
if (folder.isDirectory()) {
File[] files = folder.listFiles();
if (files != null) {
for (File file : files) {
if (file.isDirectory()) {
lstFiles.addAll(listFiles(parent, file));
} else {
String path = file.getPath();
String offset = parent.getPath();
path = path.substring(offset.length());
lstFiles.add(path);
}
}
}
}
return lstFiles;
}
}
You could simply do a normal folder recursion, returning a list of files and THEN strip of the prefix, but that's up to you
What about using the absolute path you currently have but removing the prefix from it using String.replace
You said you had the full, absolute path, say in full
then just do
String relative = full.replace(prefix, "");
If you have the input "/home/user/text", all absolute paths to files will start with /home/user/text/. If you're already able to print a list of all files under text/, then all you need to do is take the suitable substring.
The following function should visit all files under pathToDir. In the printFileName function, you can remove the /home/user/text part and print the file names
public static void gotoAllFiles(File pathToDir) {
if (pathToDir.isDirectory()) {
String[] subdirs = pathToDir.list();
for (int i=0; i<subdirs.length; i++) {
gotoAllFiles(new File(pathToDir, subdirs[i]));
}
} else {
printFileName(pathToDir);
}
}
For each file found, print the file.getAbsolutePath().substring(rootPath.length());