how to move multiple folders into 1 folder - java

I have a directory C:\Test\ that have several files and folder
example :
C:\Test\new1.txt
C:\Test\document.xls
C:\Test\presentation.pdf
C:\Test\pro_country
C:\Test\pro_libs
C:\Test\misc
C:\Test\pro_bin
C:\Test\mug
I want to MOVE (not copy ) all the folders that starts with pro into one folder
so ill have such direcotry
example :
C:\Test\new1.txt
C:\Test\document.xls
C:\Test\presentation.pdf
C:\Test\misc
C:\Test\mug
C:\Test\Newprofolder
I tried this code but I didn't know how to return the result from list files to copy them to the directory
File[] proList = direct.listFiles(new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
return name.startsWith("Pro");
}
});
String pFileDest = directory + "//" + "pcore.war";
File filepldst = new File(pFileDest);
File filePortalSrc = new File(pLocation);
try {
FileUtils.copyFile(filePortalSrc, filepldst);
} catch (IOException e) {
e.printStackTrace();
}

Files.move(new File("C:\\projects\\test").toPath(), new File("C:\\projects\\dirTest").toPath(), StandardCopyOption.REPLACE_EXISTING);
Change source and destination path

Related

Java - How to read all files in the same directory

I need to read all files in the same directory and store those files in a list. All files end in .txt and there are no subdirectory.
List<String> recipe = new ArrayList<>();
try {
recipe = Files.readAllLines(Paths.get("gyro.txt"));
}
You can get an array of files (according to the specified folder), after that you can iterate by each file in the folder and add all the characters from the file.
Can you please try to use the following code:
public static List<String> readFromAllFilesInDirectory(final String folderName) {
File folder = new File(folderName);
List<String> recipe = new ArrayList<>();
for (final File file : Objects.requireNonNull(folder.listFiles())) {
if (!file.isDirectory()) {
try {
recipe.addAll(Files.readAllLines(Paths.get(file.getPath())));
} catch (Exception e) {
}
}
}
return recipe;
}
public static void main(String[] args) {
File folder = new File("G:\\B\\1.txt");
System.out.println(readFromAllFilesInDirectory(folder.getParent()));
}
Try use the FileNameFilter class: Java FileNameFilter interface has method boolean accept(File dir, String name) that should be implemented and every file is tested for this method to be included in the file list.
File directory = new File("D://");
File[] files = directory.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".txt");
}
});
for (File file : files) {
System.out.println(file.getAbsolutePath());
}

Eclipse get linked resource path for file loading

In my Eclipse project I have a "src" folder that's linked from a one drive folder.
I have some other text files in the linked folder that I want to load with a FileReader.
How would I get this location, optimally in a way that's agnostic to whether the folder is linked or actually in the project folder. I've tried using
MyClass.class.getResource("");
But it returns me a path to the "bin" folder. I'm probably not using it right. The file I want to get is "src/de/lauch/engine/shaders/primitiveTestShader/vertexShader.vsh"
Thanks in advance!
You can create resources folder like that 'src\main\resources' and put the file after that you can run your same code . hopefully it will work.
I solved my particular issue for now but im still open to better solutions :)
public class LinkedResourceLocator {
private static Dictionary<String,String> locations;
public static String getPath(String path) {
if(locations==null) {
File projectLocal = new File(LinkedResourceLocator.class.getClassLoader().getResource("").getPath().replaceAll("%20", " ")).getParentFile();
File dotProject = new File(projectLocal.getAbsolutePath()+"\\.project");
locations = new Hashtable<String,String>();
File[] files = projectLocal.listFiles(new FileFilter(){
#Override
public boolean accept(File pathname) {
return pathname.isDirectory();
}
});
for (int i = 0; i < files.length; i++) {
locations.put(files[i].getName(), files[i].getAbsolutePath());
}
try {
BufferedReader br = new BufferedReader(new FileReader(dotProject));
StringBuilder fileContentBuilder = new StringBuilder();
String line;
while((line = br.readLine()) != null) {
fileContentBuilder.append(line.trim());
}
String fileContents = fileContentBuilder.toString();
Pattern p = Pattern.compile("<link><name>(\\w*)</name><type>\\d*</type><location>([\\w/:]*)</location></link>");
Matcher m = p.matcher(fileContents);
while(m.find()) {
locations.put(m.group(1),m.group(2));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
System.err.println("Can't locate .project file");
} catch (IOException e) {
e.printStackTrace();
System.err.println("Can't read .project file");
}
}
String locator = path.contains("/")?path.substring(0, path.indexOf("/")):path;
String restPath = path.substring(locator.length());
return locations.get(locator)+restPath;
}
}
This class gets the linked resource locations from the eclipse .project file and then converts project local paths like "src/de/lauch/engine/shaders/primitiveTestShader/vertexShader.vsh" to these linked locations.

how to filter a file with apk extension in sdcard?

I want to filter files stored in my phone with the .apk extension. I have tried the below code but it filters files found only in sdcard/file.apk
but I want it to filter the file by searching into the sub directories of sdcard also.
For example if there is an apk file inside sdcard/download/mm.apk it should filter it and also if there is another file in sdcard/New Folder/ABC/cc.apk it should filter it too.
How can I do that? thank you for your help...
ExtFilter apkFilter = new ExtFilter("apk");
File file[] =Environment.getExternalStorageDirectory().listFiles(apkFilter);
Log.i("InstallApk","Filter applied. Size: "+ file.length);
for (int i=0; i < file.length; i++)
{
Log.i("InstallApk",
"FileName:" + file[i].getName());
}
ArrayAdapter af=new ArrayAdapter<File>(this,android.R.layout.simple_list_item_1,android.R.id.text1,file);
ListView ll=(ListView) findViewById(R.id.mainListView1);
ll.setAdapter(af);
}
class ExtFilter implements
FilenameFilter {
String ext;
public ExtFilter(String ext) {
this.ext = "." + ext;
}
public boolean accept(File dir, String name)
{
return name.endsWith(ext);
}
}
You have to do it recursively. It is not enough to check for the extension, you must also verify that it is a regular file cos I can as well name a directory dir.apk. Verifying that it is a regular file is also not enough since one can name any file with any extension. Regardless, checking that it is a regular file should be enough without consideration of the intended action on these files.
public void someFunction() {
List<File> apkFiles = getApkFiles(Environment.getExternalStorageDirectory(), new ApkSearchFilter());
File file[] = apkFiles.toArray(new File[apkFiles.size()]);
Log.i("InstallApk", "Filter app\"lied. Size: " + file.length);
for (File aFile : file) {
Log.i("InstallApk", "FileName:" + aFile.getName());
}
}
List<File> getApkFiles(File file, ApkSearchFilter filter) {
if (filter.isApk(file))
return Collections.singletonList(file);
else if (filter.isDirectory(file)) {
LinkedList<File> files = new LinkedList<>();
for (File subFile : file.listFiles()) {
files.addAll(getApkFiles(subFile, filter));
}
return files;
} else return Collections.emptyList();
}
class ApkSearchFilter implements FileFilter {
boolean isApk(File file) {
return !file.isDirectory() && file.getName().matches(".*\\.apk");
}
boolean isDirectory(File file) {
return file.isDirectory();
}
#Override
public boolean accept(File file) {
return isDirectory(file) || isApk(file);
}
}
This is one in many way you can try, don't forget to add permission in manifest:
private List<String> ReadSDCard()
{
File f = new File("your path"); // Environment.getExternalStorageDirectory()
File[] files=f.listFiles();
for(int i=0; i<files.length; i++)
{
File file = files[i];
String filePath = file.getPath();
if(filePath.endsWith(".apk"))
tFileList.add(filePath);
}
return tFileList;
}

Copy all subfolders from one to another except some subfolders in java? [duplicate]

This question already has answers here:
Java copy a folder excluding some internal file
(4 answers)
Closed 9 years ago.
I want to copy all subfolders from input folder to outputDir except some subfolders. The method i am using for copy is here. but i don't know how to filter the subfolders.
public static void copyDirectory(String inputFolder, String outputDir) {
File source = new File(inputFolder);
File desc = new File(outputDir);
try {
FileUtils.copyDirectory(source, desc);
} catch (IOException e) {
e.printStackTrace();
}
}
Hi use the following code:
public static void copyDirectory(String inputFolder, String outputDir) {
File source = new File(inputFolder);
File desc = new File(outputDir);
ArrayList al=new ArrayList();//contains all your directory filter names
try {
for (File file : source.listFiles()) {
if (!al.contains(file.getName())&&file.isDirectory()) {
FileUtils.copyDirectory(source, desc);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
Try this.
public static void copyDirectory(String inputFolder, String outputDir) {
File source = new File(inputFolder);
File desc = new File(outputDir);
String name = source.getName();
String desti = desc.getPath() + "/" + name;
File destination = new File(desti);
destination.mkdir();
File[] subFolders = source.listFiles();
for (File subFolder : subFolders) {
if (condition satisfies){
// copy to destination folder
} else {
// Ignore
}
}
}

How to get a list of files from within a folder structure

im creating a program that will compile java files, at the moment i have the program compiling numerous files at a time in one particular folder. but what i want it to do is to compile all the files in a folder structure given a folder to start (eg. if given the following address C:/files_to_be_compiled, can you search all the folders within this folder to get a list of all the .class files). I have this code that is getting all the .class files from a single folder but i need to expand this to get all the .class files from all the rest of the folders in that folder given
String files;
File folder = new File("C:/files_to_compile");
File[] listOfFiles = folder.listFiles();
{
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
files = listOfFiles[i].getName();
if (files.endsWith(".class") || files.endsWith(".CLASS")) {
System.out.println(files);
}
}
}
}
how would i extend the code above get all the .class files from within all the folders in a given folder?
Maybe somwthing like
void analyze(File folder){
String files;
File[] listOfFiles = folder.listFiles();
{
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
files = listOfFiles[i].getName();
if (files.endsWith(".class") || files.endsWith(".CLASS")) {
System.out.println(files);
}
} else if (listOfFiles[i].isDirectory()){
analyze(listOfFiles[i]);
}
}
}
void start(){
File folder = new File("C:/files_to_compile");
analyze(folder);
}
This way, you're analyzing your structure recursively (Depth-first search).
public static void listFilesForFolder(String path)
{
File folder = new File(path);
File[] files = folder.listFiles();
for(File file : files)
{
if (file.isDirectory()){
listFilesForFolder(file.getAbsolutePath());
}
else if (file.isFile())
{
// your code goes here
}
}
}
// run
listFilesForFolder("C:/files_to_compile");
This answer may be of use to you.
Example code borrowed from linked answer:
public void listFilesForFolder(final File folder) {
for (final File fileEntry : folder.listFiles()) {
if (fileEntry.isDirectory()) {
listFilesForFolder(fileEntry);
} else {
System.out.println(fileEntry.getName());
}
}
}
final File folder = new File("/home/you/Desktop");
listFilesForFolder(folder);
You can use DirectoryWalker from Apache Commons to walk through a directory hierarchy and apply a filter - FileFilterUtils.suffixFileFilter(".class"). For example:
public class ClassFileWalker extends DirectoryWalker {
public ClassFileWalker() {
super(FileFilterUtils.directoryFileFilter(),
FileFilterUtils.suffixFileFilter(".class"), -1);
}
protected void handleFile(File file, int depth, Collection results) {
if(file.isFile())
results.add(file);
}
public List<File> getFiles(String location) {
List<File> files = Lists.newArrayList();
try {
walk(new File(location), files);
} catch (IOException e) {
e.printStackTrace();
}
return files;
}
}
Then use it like this:
ClassFileWalker walker = new ClassFileWalker();
List<File> files = walker.getFiles("C:/files_to_be_compiled");

Categories