Java mkdir will not work - java

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().

Related

Java application crashed due to lots of files being copied

I have an application which copies a number of files from a directory to a certain destination. The problem is that when you select a large folder it gets more intense for the app itself and then crashes. Is there any way to make it not crash? Maybe split it up into smaller parts?
This is my code:
public void startProcess(File orgDir, File destDir) {
Screen1Controller sf = new Screen1Controller();
String selectedExtension = sf.selectedExtension; // Gets selected extension from Screen1
String extensionType = sf.typeOfExtension; // Gets selected extension type from Screen1
int y = 1; // This is for searching for duplicates.. See below.
try {
File[] files = orgDir.listFiles();
for (File file : files) { // Goes through the files in the given directory
if (!file.isDirectory() && file.getName().endsWith(selectedExtension)){
File destinationPath = new File(destDir.getCanonicalPath() + "\\");
destDir = new File(destinationPath + "\\" + extensionType); // Sets the destination path
destDir.mkdir();
System.out.println("file:" + file.getCanonicalPath()); // Prints the file path
try{
String fileNameWithOutExt = file.getName().replaceFirst("[.][^.]+$", ""); // Gets the current file without the extension
File destFile = new File(destDir.getPath() + "\\" + file.getName()); // If a file of the same name exists in the dest folder
if (Files.exists(Paths.get(destFile.getPath()))) // Checks if there is a file with the same name in the folder
{
System.out.println("There is a duplicate.");
File[] destFiles = destDir.listFiles();
for (File destinationFile : destFiles) // Searches through the destination folder
{
if(destinationFile.getName().startsWith(fileNameWithOutExt)){ // Checks if the selected file has the same name as the file that's going to be moved.
y++; // Increments y by 1 to keep track of how many there are of the same/similar name
}
}
File newFile = new File(orgDir.getPath() + "\\" + fileNameWithOutExt + "." + y + selectedExtension); // Creates a new file with new name.
file.renameTo(newFile); // Renames to a unique name and moves the file to the destination folder
File destPath = new File(destDir.getPath() + "\\" + newFile.getName()); // Gets the destination path for the file
System.out.println(newFile.getCanonicalPath());
Files.copy(Paths.get(newFile.getCanonicalPath()), Paths.get(destPath.getPath())); // Renames the original file back to its original name
newFile.renameTo(new File(orgDir.getPath() + "\\" + fileNameWithOutExt + selectedExtension));
} else {
Files.copy(Paths.get(file.getPath()), Paths.get(destFile.getPath())); // Moves the file to the destination folder
}
}catch(Exception e){
e.printStackTrace();
}
} else{
startProcess(file, destDir);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
I am assuming your program is correct and this is purely memory issue. Increase the memory settings by running program with options -Xms 1024m -Xmx 1g, increase the values if necessary, be aware of your total available memory.
Will be nice to see a stack trace of exception to know for sure what caused the crash.

How to sequentially numbering files rather than overwriting them when moving

I am writing a code that could move the file from one directory to another, but I have an issue with having a file that have the same name, so I decided to number them as I don't want to overwrite them.
Assume I have file a.txt, I succeed to move to move the file with the same name then call it a_1.txt, but I am wondering what I can do if I have again a.txt?
Moreover, I feel my code is not efficient and it will be appreciated if you help me to enhance it.
My code is:
/*
* Method to move a specific file from directory to another
*/
public static void moveFile(String source, String destination) {
File file = new File(source);
String newFilePath = destination + "\\" + file.getName();
File newFile = new File(newFilePath);
if (!newFile.exists()) {
file.renameTo(new File(newFilePath));
} else {
String fileName = FilenameUtils.removeExtension(file.getName());
String extention = FilenameUtils.getExtension(file.getPath());
System.out.println(fileName);
if (isNumeric(fileName.substring(fileName.length() - 1))) {
int fileNum = Integer.parseInt(fileName.substring(fileName.length() - 1));
file.renameTo(new File(destination + "\\" + fileName + ++fileNum + "." + extention));
} else {
file.renameTo(new File(destination + "\\" + fileName + "_1." + extention));
}
}//End else
}
From the main, I called it as the following (Note that ManageFiles is the class name that the method exist in):
String source = "L:\\Test1\\Graduate.JPG";
String destination = "L:\\Test2";
ManageFiles.moveFile(source, destination);
You can use this logic:
If the file already exists in the destination, you add "(1)" to the file name (before the extension). But then you ask me: what if there's already a file with "(1)"? Then you use (2). If there's already one with (2) too, you use (3), and so on.
You can use a loop to acomplish this:
/*
* Method to move a specific file from directory to another
*/
public static void moveFile(String source, String destination) {
File file = new File(source);
String newFilePath = destination + "\\" + file.getName();
File newFile = new File(newFilePath);
String fileName;
String extention;
int fileNum;
int cont;
if (!newFile.exists()) {
file.renameTo(new File(newFilePath));
} else {
cont = 1;
while(newFile.exists()) {
fileName = FilenameUtils.removeExtension(file.getName());
extention = FilenameUtils.getExtension(file.getPath());
System.out.println(fileName);
newFile = new File(destination + "\\" + fileName + "(" + cont++ + ")" + extention);
}
newFile.createNewFile();
}//End else
}

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.

How to create multiple directories given the folder names

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.

Problem with creating a directory in Java

I am trying to create a directory in Java. I think I have provided correctly all necessary things so that I make the directory, but it is not created. You can see from my code below and the corresponding output that every element from which I compose the path of the new directory should be correct and valid.
It seems, however, that tDir.mkdir(); is not doing anything, and therefore the success variable is always false. I cannot understand why. Thank you in advance.
System.out.println("experimentDir: " + experimentDir);
System.out.println("item.getName(): " + item.getName());
System.out.println("dirName: " + dirName);
String tDirStr = experimentDir + "/" + item.getName() + "All/"
+ dirName + "DataAll";
System.out.println("tDirStr: " + tDirStr);
File tDir = new File(tDirStr);
if (tDir.exists()) {
System.out.println("EXISTS!!!");
} else {
boolean success = tDir.mkdir();
if(success) {
System.out.println("Dir created");
} else {
System.out.println("No dir created!");
}
Output:
experimentDir: /home/Documents/datasets/test-experiments
item.getName(): PosNegReviews
dirName: test
tDirStr: /home/Documents/datasets/test-experiments/PosNegReviewsAll/testDataAll
No dir created!
If you want to create multiple (nested) directories you should use mkdirs() (note the s).
you may be needing to create any parent directory that dont exist. try File.mkdirs().
public class Test1{
public static void main(String[] args)
{
String path="c:\\dir1\\dir2\\dir3\\dir4";
File dir=new File(path);
if(!dir.exists()){
dir.mkdirs();
}
}
}
above code will create dir4 inside C:\dir1\dir2\dir3. If parent folder does not exist, then it will also create.

Categories