Creating Multiple File Directories - java

I have a program that takes a file that points to a folder somewhere. I need to then make two separate directories. For example, say I have a file base that points to folder Base. I would then want to create two directories dir1 and dir2.
I know that you do the following:
//Called in constructor
File base = new File (baseFileLocString);
//Make directories
File dir1 = new File (base.getAbsoluteFilePate() + "/dir1");
dir1.mkdir();
File dir2 = new File (base.getAbsoluteFilePate() + "/dir2");
dir2.mkdir();
I do not like this way though. Ideally I could use base and make the directories without having to create new Files. I feel like there should be a more efficient way to do this. Is that the case or no?

There is an alternative
Files.createDirectory(Paths.get(base.getAbsoluteFilePath(), "dir1"));
besides it is better than File.mkdir because if something goes wrong mkdir returns false without expalnation and createDirectory throws an exception which explains what happened

Instead of
File dir1 = new File (base.getAbsoluteFilePath() + "/dir1");
You could use
File dir1 = new File (base, "dir1");
Looks better, but the performance will stay the same

Related

Processing/Java File Count Issue With File Pathway (Variable Type)

Although the Title isn't very understandable I do have a simple issue. So i'm trying to write some code in a Processing Sketch (https://processing.org/) which can count how many files are in a document. The problem is, is that it doesn't accept the variable type.
File folder = File("My File Path");
folder.listFiles().size;
It says the function File(String) doesn't exist. When I try to put the file path without quation marks, it still doesn't work!
If you have a solution then please use a functioning example so that I know how it works. Thanks for any help!
As Joakim Danielson says it is constructor so you need to use new keyword.
Below code will work for you.
File folder = new File("My File Path");
int fileLength = folder.listFiles().length;
It's a constructor so you need to use new
File folder = new File("My File Path");
//To get the number of files in the folder
folder.listFiles().length;
Assuming the "My File Path" folder is inside your sketch you need to provide the path to your sketch. Luckily Processing already provides a helper function: sketchPath()
Here's an example:
File folder = new File(sketchPath("My File Path"));
println("folder.exists: " + folder.exists());
if(folder.exists()){
println(folder.listFiles().length + " files and/or directories");
}else{
println("folder does not exist, double check the path");
}
Bare in mind there's also a dataPath() function which points to a folder named data in your sketch folder. The data folder is typically used for storing external data (e.g. assets (raster or vector images/Processing font files) or raw data (binary/text/csv/xml/json/etc.)). This is useful to separate your sketch source files from the data to be loaded/accessed by your sketch.
Also, Processing has a few utility functions for listing files and folders.
Be sure to check out Processing > Examples > Topics > File IO > DirectoryList
The example includes less documented functions such as listFiles() (which returns an array of java.io.File objects based on the filters set) or listPaths (which returns an array of String objects: just the paths).
The options and filters are quite handy, for example if you want to list directories only and ignore files you can simply write simply like:
println("directories: " + listFiles(sketchPath("My File Path"),"directories").length);
For example if want to list all the wav files in a data/audio directory inside the sketch you can use:
File[] files = listFiles(dataPath("audio"), "files", "extension=wav");
This will ignore directories and any other file that does not have .wav extension.
To make this answer complete, here are a few more details on the options for listFiles/listPaths from Processing's source code:
"relative" -> no effect with the Files version, but important for listPaths
"recursive"-> traverse nested directories
"extension=js" or "extensions=js|csv|txt" (no dot)
"directories" -> only directories
"files" -> only files
"hidden" -> include hidden files (prefixed with .) disabled by default

Can't create .txt files

I have it like this:
file=new File(pathString+"/TileRecordings/",jTextField1.getText()+".txt");
and then after null checking etc...
file.createNewFile();
Thing is, if the texfield value was 'test' it would create 'text.txt' AS A FOLDER. Not an actual text file.
Is this a Ubuntu only thing? How do I force it to literally create a text file, not a folder named 'test.txt'.
Maybe try features from java.nio.file
for example:
Path temp = Paths.get(pathString+"/TileRecordings/"+jTextField1.getText()+".txt");
Files.write(temp, contentToSave.toString().getBytes());

Generate a file next to the jar file containing the code

I have a jar with my application that should create a file next to it. So in folder I will have this :
Source
|_ MyApplication.jar
|_ generatedFile.txt
Easy thing I thought... nope.. I am lost... I have a code like this:
URL location = MyClass.class.getProtectionDomain().getCodeSource().getLocation();
String path = location.getFile().substring(0, location.getFile().lastIndexOf("/MyContext"));
File file = new File(fileName + ".txt");
File file1 = new File(path + "/MyFileName.txt");
File file2 = new File(path.substring(1) + "/MyFileName.txt");
I tried different combinations, googled alot and I am lost... if I get for example
file1.getPath();
file2.getAbsolutePath();
and so on, the paths are correct... but the file isn't generated... Only working case is the first one, but that is located inside the jar and I don't want that.
I also tried to moving the existing file outside using
Paths.move(...
but that hasn't helped me at all..
Can someone help me with this ? And explain to me why isn't the examples above working ? Thanks..
The call File file = new File("my path string"); just creates a Java File Object instance in memory. You need to write something to the actual file you are targeting. The simplest way to create an empty file is to call file.createNewFile().

Why app_ appears while creating directory using ContextWraper.getDir

In my app, I used this code:
File DirectoryPath = cw.getDir("custom", Context.MODE_PRIVATE);
While creating a directory, and it returns:
/data/data/com.custom/app_custom**
So my question is why this app_ appears along with directory name. I know its default, but what actually it means?
And secondly, how can I create a sub-directory inside my directory i.e. app_custom in this case. if anyone knows please help me to understand this concept of getDir.
As far as I think, automatic "app_" added to user created data folders avoid any conflicts with system predefined application folders (folders inside application data folder i.e. cache, contents, databases etc. which are automatically created).
One method to create a sub folder inside those "app_..." folders, get absolute path of "app_..." folder, append required folder name to that and create using mkdirs()
e.g.
File dir = new File(newFolderPath);
dir.mkdirs()
Note: sub folders do not get "app_..." prefix
You can create a new Directory using the path that you are getting from getDir(),
File file = getDir("custom", MODE_PRIVATE);
String path = file.getAbsolutePath();
File create_dir = new File(path+"/dir_name");
if(!create_dir.exists()){
create_dir.mkdir();
}

Reading .txt file from another directory

The code I am running is in /Test1/Example. If I need to read a .txt file in /Test1 how do I get Java to go back 1 level in the directory tree, and then read my .txt file
I have searched/googled and have not been able to find a way to read files in a different location.
I am running a java script in an .htm file located at /Test1/Test2/testing.htm. Where it says script src=" ". What would I put in the quotations to have it read from my file located at /Test1/example.txt.
In Java you can use getParentFile() to traverse up the tree. So you started your program in /Test1/Example directory. And you want to write your new file as /Test1/Example.txt
File currentDir = new File(".");
File parentDir = currentDir.getParentFile();
File newFile = new File(parentDir,"Example.txt");;
Obviously there are multiple ways to do this.
You should be able to use the parent directory reference of "../"
You may need to do checks on the OS to determine which directory separation you should be using ['\' compared to '/']
When you create a File object in Java, you can give it a pathname. You can either use an absolute pathname or a relative one. Using absolutes to do what you want would require:
File file = new File("/Test1/myFile.txt");
if(file.canRead())
{
// read file here
}
Using relatives paths if you want to run from the location /Test1/Example:
File file = new File("../myFile.txt");
if(file.canRead())
{
// read file here
}
I had a similar experience.
My requirement is: I have a file named "sample.json" under a directory "input", I have my java file named "JsonRead.java" under a directory "testcase". So, the entire folder structure will be like untitled/splunkAutomation/src and under this I have folders input, testcase.
once after you compile your program, you can see a input file copy named "sample.json" under a folder named "out/production/yourparentfolderabovesrc/input" and class file named "JsonRead.class" under a folder named "out/production/yourparentfolderabovesrc/testcase". So, during run time, Java will actually refer these files and NOT our actual .java file under "src".
So, my JsonRead.java looked like this,
package testcase;
import java.io.*;
import org.json.simple.JSONObject;
public class JsonRead{
public static void main(String[] args){
java.net.URL fileURL=JsonRead.class.getClass().getResource("/input/sample.json");
System.out.println("fileURL: "+fileURL);
File f = new File(fileURL.toURI());
System.out.println("fileIs: "+f);
}
}
This will give you the output like,
fileURL: file:/C:/Users/asanthal/untitled/out/production/splunkAutomation/input/sample.json
fileIs: C:\Users\asanthal\untitled\out\production\splunkAutomation\input\sample.json
It worked for me. I was saving all my classes on a folder but I needed to read an input file from the parent directory of my classes folder. This did the job.
String FileName = "Example.txt";
File parentDir = new File(".."); // New file (parent file ..)
File newFile = new File(parentDir,fileName); //open the file

Categories

Resources