Java File Name Printing - java

I am trying to print name of files from two folders, and this code compiles but not giving anything on running it.
The main target here is to find common name files in two folders, I have stored file names in two arrays and then i will applying sorting and will find common files.
package javaapplication13;
import java.io.File;
import java.util.*;
public class ListFiles1
{
public static void main(String[] args)
{
String path1 = "C:/";
String path2 = "D:/";
File folder1 = new File(path1);
File folder2 = new File(path2);
String[] f1=folder1.list();
File[] listOfFiles1 = folder1.listFiles();
File[] listOfFiles2 = folder2.listFiles();
ArrayList<String> fileNames1 = new ArrayList<>();
ArrayList<String> fileNames2 = new ArrayList<>();
for (int i = 0; i < listOfFiles1.length; i++)
{
if (listOfFiles1[i].isFile())
{
fileNames1.add(listOfFiles1[i].getName());//wow
System.out.println(listOfFiles1[i].getName());
}
}
for (int i = 0; i < listOfFiles2.length; i++)
{
if (listOfFiles2[i].isFile())
{
fileNames2.add(listOfFiles2[i].getName());//seriously wow
}
}
}
}

Loop through both the ArrayLists you have. Each ArrayList contains the file names as it is. You'll need a nested loop (a loop inside a loop). In the core of the nested loops, you want to do a compare between current position of each ArrayList. You can use .equals() method for this. The pseudo code is something like:
//create a new ArrayList called "commonNameList"
// loop through fileNames1 with position variable "i"
//loop through fileNames2 with position variable "j"
//tempFileName1 = fileNames1.get(i)
//tempFileName2 = fileNames2.get(j)
//if tempFileName1 equals tempFileName2
//commonNameList.add(tempFileName1)
Check these out:
http://mathbits.com/MathBits/Java/Looping/NestedFor.htm
Simple nested for loop example
How do I compare strings in Java?

The main target here is to find common name files in two folders, I have stored file names in two arrays and then i will applying sorting and will find common files.
I don't like the two array thing. Also, a duplicate file should probably have the same length as well as the same name. If you are really going for just names, you can remove the f.length() == temp.length() part of the condition.
private static void findDups(String dirName1, String dirName2){
File dir1 = new File(dirName1);
File dir2 = new File(dirName2);
Map<String,File> fileMap = new HashMap<String,File>();
File[] files = dir1.listFiles();
for(File f : files){
fileMap.put(f.getName(),f);
}
files = dir2.listFiles();
StringBuilder sb = new StringBuilder(100);
for(File f : files){
File temp = fileMap.get(f.getName());
if(temp != null && f.length() == temp.length()){
sb.append("Found duplicate files: ")
.append(temp.getAbsolutePath())
.append(" and ")
.append(f.getAbsolutePath());
System.out.println(sb);
sb.delete(0,sb.length());
}
}
}

Related

Java code to get the list of file name from a folder

I have a scenario where around 5600 files are present.
I am able to retrieve the file names by using the below code:
String path = "D:\\Projects worked upon\\ANZ\\Anz new\\Files\\329703588_20160328124733595\\Output"; 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();
if (files.toLowerCase().endsWith(".xml"))
{
System.out.println(files);
}
, but i need only the first part For Eg:if the file name in folder is "abc_Transformed.xml" , i require only abc .. How to get it ?
You can use the substring method to find first string.
if (files.toLowerCase().endsWith(".xml"))
{
String result = files.substring(0, files.indexOf("_"));
System.out.println(result);
}
your whole code
String path = "D:\\Projects worked upon\\ANZ\\Anz new\\Files\\329703588_20160328124733595\\Output"; 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();
if (files.toLowerCase().endsWith(".xml"))
{
String result = files.substring(0, files.indexOf("_"));
System.out.println(result);
}
The information about the files is basically irrelevant. You are after some basic String manipulation functions.
You could try something using String.split() like:
String[] pieces = files.split("_");
String first = pieces[0]; // should be equal to "abc"
Or something using String.indexOf() and String.substr() like:
int indexOfUnderscore = files.indexOf("_");
String first = files.substr(0, indexOfUnderscore); // should be equal to "abc"
If you're new to Java, it's worth spending the time to review all the String functions.

Convert a file array to string array JAVA

I need some help.
I use this code to get the files in a folder as an array .
String fileDir = Directorty;
File dir = new File(fileDir);
FileFilter fileFilter = new WildcardFileFilter("*.html");
files = dir.listFiles(fileFilter);
But I want to write a file with only the files in that folder and not the path.
The result is:
[C:\Askeladden-17-12-2014\.html, C:\Askeladden-17-12-2014\barnetv.html, C:\Askeladden-17-12-2014\britiskebiler.html, C:\Askeladden-17-12-2014\danser.html, C:\Askeladden-17-12-2014\disipler.html, C:\Askeladden-17-12-2014\donald.html, C:\Askeladden-17-12-2014\ekvator.html, C:\Askeladden-17-12-2014\engelskspraak.html]
But I want to have it without the path
C:\Askeladden-17-12-2014\
I have been looking around the webs to find some answers, but no luck.
Using this:
strFiles = Arrays.toString(files);
Gives a string presented as an array with [] in each end, and I am not able to get
strFiles.replace("C:\\Askleladden" + date +"\\", "");
to work.
You have to iterate the files array and call getName() for each file:
String[] names = new String[files.length];
for (int i = 0; i < files.length; i++) {
names[i] = files[i].getName();
}
Java 1.8, if you want get as List, just remove cast and to array
String[] files = (String[])Arrays.asList(dir.listFiles(filefilter))
.stream().map(x->x.getName())
.collect(Collectors.toList())
.toArray();
Please find the solution below with proper comments.
import java.io.File;
import java.io.FileFilter;
public class fileNames {
public static void main(String args[]){
//Get the Directory of the FOLDER
String fileDir = "/MyData/StudyDocs/";
// Save it in a File object
File dir = new File(fileDir);
//FileFilter fileFilter = new WildcardFileFilter("*.html");
//Capture the list of Files in the Array
File[] files = dir.listFiles();
for(int i = 0; i < files.length; i++){
System.out.println(files[i].getName());
}
}
}
Use Files getName() method:
File file = new File("myFolder/myFile.png");
System.out.println(file.getName()); //Prints out myFile.png

Change files names in parent and child directories

I am a beginner in Java trying to work with Files and Directories. I wanted to create a program where I could change file names automatically while searching through all the child directories for file names that are not valid. I am actually trying to load a huge amount of files on to a server but the server settings do not allow file names containing special characters. To start with I was able to write the code where if I pass the path to a directory it renames all the files with invalid names in that directory:
public class reNaming {
public static String baseLoc = "C:/Users/Developer/Desktop/.../Data Cleanup";
public static void main(String[] args) {
//LinkedList<File> fileList = new LinkedList<File>();
File obj = new File(baseLoc);
int count = 0;
for (File file: obj.listFiles())
{
String origName = file.getName();
if (origName.contains("&") || origName.contains("#") || origName.contains("#"))
{
System.out.println("Original name: "+origName);
origName = origName.replaceAll("&", "_and_");
origName = origName.replaceAll("#", "_at_");
String newName = origName.replaceAll("#", "_");
System.out.println("New Name: "+newName);
String newLoc = baseLoc+"/"+newName;
File newFile = new File(newLoc);
System.out.println(file.renameTo(newFile));
count++;
}
}
}
}
Now I want to do the same but only this time I want all the files to be reNamed even in the child directories. Can somebody please guide me how I can achieve that?
Recursion is your friend
/**Removes 'invalid' characters (&,#,#) from pathnames in the given folder, and subfolders, and returns the number of files renamed*/
public int renameDirectory(File base){
//LinkedList<File> fileList = new LinkedList<File>();
int count=0;//count the renamed files in this directory + its sub. You wanted to do this?
//Process each file in this folder.
for (File file: base.listFiles()){
String origName = file.getName();
File resultFile=file;
if (origName.contains("&") || origName.contains("#") || origName.contains("#")){
//I would replace the if statement with origName.matches(".*[&##].*") or similar, shorter but more error prone.
System.out.println("Original name: "+origName);
origName = origName.replaceAll("&", "_and_");
origName = origName.replaceAll("#", "_at_");
String newName = origName.replaceAll("#", "_");
System.out.println("New Name: "+newName);
String newLoc = baseLoc+File.separator+newName;//having "/" hardcoded is not cross-platform.
File newFile = new File(newLoc);
System.out.println(file.renameTo(newFile));
count++;
resultFile=newFile;//not sure if you could do file=newFile, tired
}
//if this 'file' in the base folder is a directory, process the directory
if(resultFile.isDirectory()){//or similar function
count+=renameDirectory(resultFile);
}
}
return count;
}
Move the code you have to a utility method (e.g. public void renameAll(File f){}). Have a condition that checks if the file is a directory and recursively call your method with it's contents. After that do what you are currently doing.
public void renameAll(File[] files){
for(File f: files){
if(f.isDirectory){
renameAll(f.listFiles());
}
rename(f);
}
}
public void rename(File f){ }

Is it possible to store files of a folder in dynamic array in Java [duplicate]

This question already has answers here:
Finding common Files from two arrays
(2 answers)
Closed 9 years ago.
I am trying to find same name files in two folders.
I used File and listed names of file in two array list.
then i added common name files in two folders to a new arraylist and going to apply diff to find if these files are different or not.
As i have only stored name of files in Array List, i can't apply operation on those files directly.
Someone told me that by the use of dynamic array one can save files in Java...
My code till now with help of some great friends :
import java.io.File;
import java.util.*;
public class ListFiles1
{
public static void main(String[] args)
{
String path1 = "C:\\Users\\hi\\Downloads\\IIT Typing\\IIT Typing";
String path2 = "C:\\Users\\hi\\Downloads\\IIT Typing\\IIT Typing";
File folder1 = new File(path1);
File folder2 = new File(path2);
String[] f1=folder1.list();
File[] listOfFiles1 = folder1.listFiles();
File[] listOfFiles2 = folder2.listFiles();
ArrayList<String> fileNames1 = new ArrayList<>();
ArrayList<String> fileNames2 = new ArrayList<>();
for (int i = 0; i < listOfFiles1.length; i++)
{
if (listOfFiles1[i].isFile())
{
fileNames1.add(listOfFiles1[i].getName());
// System.out.println(f1[i] + " is a file");
}
}
for (int j = 0; j < listOfFiles2.length; j++)
{
if (listOfFiles2[j].isFile())
{
fileNames2.add(listOfFiles2[j].getName());
}
}
ArrayList<String> commonfiles = new ArrayList<>();
for (int i = 0; i < listOfFiles1.length; i++)
{
for (int j = 0; i < listOfFiles2.length; j++)
{
String tempfilename1;
String tempfilename2;
tempfilename1=fileNames1.get(i);
tempfilename2 = fileNames2.get(j);
if(tempfilename1.equals(tempfilename2))
{
commonfiles.add(tempfilename1);
System.out.println(commonfiles);
}
}
}
}
}
Rather then having an ArrayList of Strings of the file names, just have an ArrayList of Files
List<File> filesList1 = Arrays.asList(folder1.listFiles());
List<File> filesList2 = Arrays.asList(folder2.listFiles());
Then when comparing if they have the same name then do your check of if it is a file and has the same name, then you have the reference to the File object and not just the name so you can read the files and see if they are the same.
for (File f1 : filesList1)
{
if(f1.isFile())
{
for (File f2 : filesList2)
{
if(f2.isFile() && f1.getName().equals(f2.getName))
{
commonfiles.add(f1.getName());
System.out.println(f1.getName());
}
}
}
}
This could be done way more efficiently with sets though
I'm not sure what your question actually is here, but I suggested that you use:
Set<String> dir1Files = new HashSet<String>();
Set<String> dir2Files = new HashSet<String>();
// load the sets with the filenames by iterating the File.listFiles() value, and using File.isFile() and File.getName() - just like your existing code
dir1Files.retainAll(dir2Files);
// now dir1Files contains the filenames that are the same in both directories
And if you need to work with the file itself, just recreate the File object:
File dir1File = new File(folder1, filename);
import java.io.File;
public class FileNameMatcher
{
public static void main(String[] args)
{
File folder1 = new File("C:/Users/pappu/Downloads");
File folder2 = new File("C:/Users/pappu");
for(String fileFromFolderOne:folder1.list())
{
for(String fileFromFolderTwo:folder2.list())
{
if(fileFromFolderOne.equals(fileFromFolderTwo))
{
System.out.println("match found");
System.out.println("file name is ===>>>"+fileFromFolderOne);
}
}
}
}
}

sampling files from a folder

I have a folder containing 100000 files, and need to get 1000 files from this folder through random sampling. Are there any sample functions that I can use to sample from folder? In addition, how to copy the sampled files to another folder?
Random selection could follow along the following lines
File files[] = new File("/path/to/files").listFiles();
Map<Integer, File> selection = new HashMap<Integer, File>(1000);
while (selection.size() < 1000) {
int value = (int)Math.round(Math.random() * files.length);
if (!selection.containsKey(value)) {
selection.put(value, files[value]);
}
}
for (File file : selection.values()) {
System.out.println(file);
}
Essentially, you need to grab a list of the available files and the randomly pick through the list until you have enough of a sample. Check out java.io.File
There are plenty of examples of file copying over the net (and SO). If you're really stuck you could have a look the IO Trail or Apache Commons IO which I believe has a utility class capable of coping files
UPDATED
As suggested by Andrew, you could simply shuffle the file list and pull the first 1000 elements...
File files[] = new File("/path/to/files").listFiles();
List<File> selection = null;
List<File> fileList = new ArrayList<File>(Arrays.asList(files));
Collections.shuffle(fileList);
selection = fileList.subList(0, Math.min(1000, fileList.size()));
for (File file : selection) {
System.out.println(file);
}
Please try this
public static void main(String args[]) throws Exception
{
File f= new File("E:/Eclipse-Leo/Test/src/test/Desktop1");
List<File> randomFiles = new ArrayList<File>();
List<Integer> randNumber = new ArrayList<Integer>();
if(f != null && f.isDirectory()){
File[] files = f.listFiles();
Random randomGenerator = new Random();
int idx = 1;
while(idx <101 && idx >= 1)
{
int randTemp = randomGenerator.nextInt(1000);
if(!randNumber.contains(randTemp))
{
randNumber.add(randTemp);
randomFiles.add(files[randTemp]);
idx++;
}
}
}
}
File[] files = dir.listFiles();
Then just use files.length and a random number generator to index into the array.

Categories

Resources