How to create multiple directories given the folder names - java

I have a list of files, the names of these files are are made of a classgroup and an id (eg. science_000000001.java)
i am able to get the names of all the files and split them so i am putting the classgroups into one array and the ids in another.. i have it so that the arrays cant have two of the same values.
This is the problem, i want to create a directory with these classgroups and ids, an example:
science_000000001.java would be in science/000000001/science_000000001.java
science_000000002.java would be in science/000000002/science_000000002.java
maths_000000001.java would be in maths/000000001/maths_000000001.java
but i cannot think of a way to loop through the arrays correctly to create the appropriate directories?
Also i am able to create the folders myself, its just getting the correct directories is the problem, does anyone have any ideas?

Given:
String filename = "science_000000001.java";
Then
File fullPathFile = new File(filename.replaceAll("(\\w+)_(\\d+).*", "$1/$2/$0"));
gives you the full path of the file, in this case science/000000001/science_000000001.java
If you want to create the directory, use this:
fullPathFile.getParentFile().mkdirs();

The above answer is really good for creating new files with that naming convention. If you wanted to sort existing files into their relative classgroups and Ids you could use the following code:
public static void main(String[] args) {
String dirPath = "D:\\temp\\";
File dir = new File(dirPath);
// Get Directory Listing
File[] fileList = dir.listFiles();
// Process each file
for(int i=0; i < fileList.length; i++)
{
if(fileList[i].isFile()) {
String fileName = fileList[i].getName();
// Split at the file extension and the classgroup
String[] fileParts = fileName.split("[_\\.]");
System.out.println("One: " + fileParts[0] + ", Two: " + fileParts[1]);
// Check directory exists
File newDir = new File(dirPath + fileParts[0] + "\\" + fileParts[1]);
if(!newDir.exists()) {
// Create directory
if(newDir.mkdirs()) {
System.out.println("Directory Created");
}
}
// Move file into directory
if(fileList[i].renameTo(new File(dirPath + fileParts[0] + "\\" + fileParts[1] + "\\" + fileName))) {
System.out.println("File Moved");
}
}
}
}
Hope that helps.

Related

LibGdx not getting files from within a directory

In my assets folder, I have a directory called "maps" which contains a list of images I want to load.
When running:
Gdx.files.internal("maps").exists();
This returns true
and:
Gdx.files.internal("maps/Africa.png").exists();
also returns true
However, trying to list these files seems to be unfeasible:
Gdx.files.internal("maps").list().length;
returns a value of 0 for the number of files in that directory
Moreover:
Gdx.files.internal("maps").isDirectory();
returns false.
This is very puzzling for what could have seemed to been a very straightforward way of getting files from a directory.
Does anyone have any ideas to circumvent this?
Since desktop builds cannot use the list() method on internal directories, I created this script to write the file names to a text file. It uses Apache commons.io (you can put compile "commons-io:commons-io:2.4+" into your build.gradle to include it in your desktop module):
//directories within assets that you want a catalog of
static final String[] directories = {
"completeMaps",
"typeAMaps",
"typeBMaps",
"sfx",
"music"
};
public static void main (String[] args){
String workingDir = System.getProperty("user.dir");
for (String dir : directories){
File directory = new File(workingDir + "/" + dir);
File outputFile = new File(directory, "catalog.txt");
FileUtils.deleteQuietly(outputFile); //delete previous catalog
File[] files = directory.listFiles();
try {
for (int i = 0; i < files.length; i++) {
FileUtils.write(outputFile, files[i].getName() + (i == files.length - 1 ? "" : "\n"), true);
}
} catch (IOException e){
Util.logError(e);
}
}
}
Then to get a file list in a directory:
private FileHandle[] readDirectoryCatalogue (String directory){
String[] fileNames = Gdx.files.internal(directory + "/catalog.txt").readString().split("\n");
FileHandle[] files = new FileHandle[fileNames.length];
for (int i = 0; i < fileNames.length; i++) {
files[i] = Gdx.files.internal(directory + "/" + fileNames[i].replaceAll("\\s+",""));
}
return files;
}

Java mkdir will not work

I have this method where I am trying to create a sub directory into the stations folder. All needed directories are made before this method is called. All folders have the normal positions and are not hidden.
private void moveFiles(){
String[] dates = getDates();
//File oldFile = new File("/stations/CurrentFiles/");
File newFile = new File("/stations/" + dates[0].replaceAll("/", "-") + "-" + dates[1].replaceAll("/", "-") + "_" + System.currentTimeMillis() + "/");
if(!newFile.exists()){
if(newFile.mkdir()){
System.out.println(newFile.isHidden());
}else{
System.out.println("error");
System.out.println(newFile.isHidden());
}
}
}
Not understanding what could make it not make the directory.
I would check to make sure you have write permissions for that directory; try newFile.canWrite().

Remove whitespace from all filenames in directory - Java

I have directory of images and I want to rename the files by removing all of the whitespace in the name.
So let's say I have a file name called " f il ena me .png" (I plan on checking all of the file names in the directory). How might I remove all of the spaces and rename the image so that the correct file name (for this specific case) is "filename.png".
So far I have tried the following code and it actually deletes the image in the directory (I'm testing it on one image in the directory currently).
public static void removeWhiteSpace (File IBFolder) {
// For clarification:
// File IBFolder = new File("path/containing/images/folder/here");
String oldName;
String newName;
String temp;
for (File old : IBFolder.listFiles()) {
oldName = old.getName();
temp = oldName.replaceAll(" ", "");
// I have also tried:
// temp = oldName.replaceAll("//s", "");
temp = temp.split(".png")[0];
newName = temp + ".png";
System.out.println(newName);
old.renameTo(new File(newName));
}
}
I think it doesn't delete the images, but moves them to your current working directory and renames it to newName, but since newName is missing a path information, it will rename / move it to "./" (from wherever you run your program).
I think you have a bug in these lines:
temp = temp.split(".png")[0];
newName = temp + ".png";
"." is a wilcard character and lets say your file is called "some png.png", newName would be "som.png", because "some png.png".replaceAll(" ", "").split(".png") results in "som".
If by any reason you need the String.split() method, please properly quote the ".":
temp = temp.split("\\.png")[0];
Ignoring naming conventions (which I intend to fix later) here is the solution I finalized.
public static void removeWhiteSpace (File IBFolder) {
// For clarification:
// File IBFolder = new File("path/containing/images/folder/here");
String oldName;
String newName;
for (File old : IBFolder.listFiles()) {
oldName = old.getName();
if (!oldName.contains(" ")) continue;
newName = oldName.replaceAll("\\s", "");
// or the following code should work, not sure which is more efficient
// newName = oldName.replaceAll(" ", "");
old.renameTo(new File(IBFolder + "/" + newName));
}
}

Add a File object to an array of File objects [duplicate]

This question already has answers here:
How to add new elements to an array?
(19 answers)
Closed 8 years ago.
First, let me show you the code I have so far:
public void populateArray(){
//NOTE: THIS METHOD SHOULD BE RUN FIRST. Many of the methods in this class rely on a populated file array to function.
// This method will populate our file array.
// First, we note the directory we want to pull files from.
File folder = new File("HR");
File dir = new File("");
File file = new File("");
//Then we fill an array with the list of documents in that directory
//This will also include folders.
int count = 0;
allDocs = folder.listFiles();
int fileCount = 0;
int dirCount = 0;
System.out.println("Displaying contents of directory...");
while (count < allDocs.length){
System.out.println("Found: " + allDocs[count]);
count++;
}
System.out.println("Sorting directories and files separately...");
count = 0;
while (count < allDocs.length){
if (allDocs[count].isDirectory()){
dir = new File(allDocs[count].getPath());
dirs[dirCount] = dir;
System.out.println("Document " + allDocs[count].getPath() + " sorted into -Directory- array at position " + dirCount);
dirCount++;
}
else{
file = new File(allDocs[count].getPath());
files[fileCount] = file;
System.out.println("Document " + allDocs[count].getPath() + " sorted into -File- array at position " + fileCount);
fileCount++;
}
count++;
}
return;
}
files, dirs, and allDocs are arrays declared within the class outside of any methods.
allDocs is the array I use to get every directory and file in the directory of interest, HR. I do this with allDocs = folder.listFiles();
I want files to be the array to store all of the files in the directory HR, and I want dirs to be the array to store all of the directories in HR, but I don't want to store any of the contents of the directors in HR.
I try to do this with the loop under the println "Sorting directories and files separately."
The problem is here:
else{
file = new File(allDocs[count].getPath());
files[fileCount] = file;
System.out.println("Document " + allDocs[count].getPath() + " sorted into -File- array at position " + fileCount);
fileCount++;
}
It's here because the first element in allDocs is a file. The problem also occurs when the first element is a directory. The problem is a null pointer exception on the files[fileCount] = file; line, which I don't understand. "file" is not null, I just assigned it a value. Of course files[fileCount] is null in this case, but why does that matter if I'm assigning it a value?
Files declaration:
public class Methods
{
private static File[] files;
You might prefer to simplify:
List<File> fileList = new ArrayList<>();
List<File> dirList = new ArrayList<>();
while (count < allDocs.length){
if (allDocs[count].isDirectory()){
dirList.add(allDocs[count]);
System.out.println("Document " + allDocs[count].getPath()
+ " sorted into -Directory- array at position " + dirCount);
dirCount++;
}
else{
fileList.add[allDocs[count]);
System.out.println("Document " + allDocs[count].getPath()
+ " sorted into -File- array at position " + fileCount);
fileCount++;
}
count++;
}
dirs = dirist.toArray(new File[dirList.size()]);
dirCount = dirs.length;
files = fileList.toArray(new File[fileList.size()]);
fileCount = files.length;
Using a List<File> instead of File[] seems appropiate, as you do not know the array sizes in advance, and you need:
File[] files = new File[n];
if intending to fill in a File:
files[fileCount] = ...
You might have forgotten to allocate the array - like this:
java.io.File [] files = new java.io.File[10];
If you only declared it like this:
java.io.File [] files;
files will be null and files[fileCount] will cause a NullPointerException.
As mentioned in the comments, you might like to change it to:
java.util.List<java.io.File> files = new ArrayList<>();
and add the files like:
files.add(file);
This way you won't have to know the number of entries in advance.

Add index to filename for existing file (file.txt => file_1.txt)

I want to add an index to a filename if the file already exists, so that I don't overwrite it.
Like if I have a file myfile.txt and same time myfile.txt exists in destination folder - I need to copy my file with name myfile_1.txt
And same time if I have a file myfile.txt, but destintation folder contains myfile.txt and myfile_1.txt - generated filename has to be myfile_2.txt
So the functionality is very similar to the creation of folders in Microsoft operating systems.
What's the best approach to do that?
Using commons-io:
private static File getUniqueFilename( File file )
{
String baseName = FilenameUtils.getBaseName( file.getName() );
String extension = FilenameUtils.getExtension( file.getName() );
int counter = 1
while(file.exists())
{
file = new File( file.getParent(), baseName + "-" + (counter++) + "." + extension );
}
return file
}
This will check if for instance file.txt exist and will return file-1.txt
You might also benefit from using the apache commons-io library. It has some usefull file manipulation methods in class FileUtils and FilenameUtils.
Untested Code:
File f = new File(filename);
String extension = "";
int g = 0;
int i = f.lastIndexOf('.');
extension = fileName.substring(i+1);
while(f.exists()) {
if (i > 0)
{ f.renameTo(f.getPath() + "\" + (f.getName() + g) + "." + extension); }
else
{ f.renameTo(f.getPath() + "\" + (f.getName() + g)); }
g++;
}
Try this link partly answers your query.
https://stackoverflow.com/a/805504/1961652
DirectoryScanner scanner = new DirectoryScanner();
scanner.setIncludes(new String[]{"**/myfile*.txt"});
scanner.setBasedir("C:/Temp");
scanner.setCaseSensitive(false);
scanner.scan();
String[] files = scanner.getIncludedFiles();
once you have got the correct set of files, append a proper suffix to create a new file.

Categories