Create file in Java with all parent folders [duplicate] - java

This question already has answers here:
How to create a new file together with missing parent directories?
(3 answers)
Closed 3 years ago.
In java any way to create a file without its parent foler and parent's parent folder
Here is the full path of the file to be created.D:\test3\ts435\te\util.log
There is not any folder existing in this path, which means there is nothing under D:\.
In java, when I create this file
File testFile=new File(filePath);
testFile.createNewFile();
It says it cannot find the path. Then I try to create the parent folder 'te'. Then it fail again, saying it cannot find the parent folder 'ts435'.
Is there any way to create the file forcely? To create the file with or without its parents and upper level folders exist.
Update 2019-06-28:
Hi guys, I finally find the reason. There are two mehtods, mkdir() and mkdirs(). When the destination folder's parent folder not exist, mkdir() will return false because it cannot forcely build the entire folder struncture.
However, mkdirs() can do this magic. It can build the entire folder chain whether parent folder exist or not.

You can ensure that parent directories exist by using this method File#mkdirs().
File f = new File("D:\\test3\\ts435\\te\\util.log");
f.getParentFile().mkdirs();
// ...
If parent directories don't exist then it will create them.

File testFile=new File("D:\\test3\\ts435\\te\\util.log");
if(! testFile.getParentFile().exists()) {
testFile.getParentFile().mkdirs();
}
testFile.createNewFile();

You can use following method to create file and directory together.
public static String createFile(String filePath, String fileName) throws BotServiceException {
File directory = new File(filePath);
if (!directory.exists() && !directory.mkdirs()) {
throw new Exception("Directory does not exist and could not be created");
}
File newFile = new File(filePath+ File.separator + fileName);
boolean isSuccess = newFile.createNewFile();
return newFile.getAbsolutePath();
}

Related

How to get rid of - "java.io.IOException: The system cannot find the path specified"

I am trying to create a file and write to it, but I'm getting error in my path.
Here is my code:
#Value("${base.location}")
private String folderName;
if (StringUtils.isBlank(dateFileName)) {
setdateFileName(new StringBuilder().append("MY_FILE")
.append(".txt").toString());
}
dateFile = new File(
new StringBuilder().append(folderName).append(File.separator).append(dateFileName).toString());
if (!dateFile.exists()) {
try {
dateFile.mkdir();
dateFile.createNewFile(); //error
}
You can’t have a folder and a file with the same name in the same path location.
That’s why this code fails:
dateFile.mkdir();
dateFile.createNewFile();
Here you’re first creating a folder, and then you’re attempting to create a file with the same path name. You need to choose a different name for the file.
I’m guessing you potentially intended the following instead:
dateFile.getParentFile().mkdirs();
dateFile.createNewFile();
I.e. create the parent folder of your file (including all its parents, as necessary), and then create the file inside it.

Trying to create a new file throws FileNotFoundException but file exists in the same package [duplicate]

This question already has answers here:
java.io.FileNotFoundException: the system cannot find the file specified
(8 answers)
Closed 4 years ago.
I have a csv file in the same path as everything else. Now, when I try to create a File object:
public void getMenu() {
File fileMenu = new File("FastFoodMenu.csv");
try {
Scanner inputStream = new Scanner(fileMenu);
while (inputStream.hasNext()) {
String data = inputStream.next();
System.out.println(data);
}
} catch (FileNotFoundException ex) {
Logger.getLogger(FileHandler.class.getName()).log(Level.SEVERE, null, ex);
}
}
it throws a FileNotFoundException.
the absolute path to all files in the project is:
C:\Users\kenyo\Documents\NetBeansProjects\OrderFastFood\src\fastfoodorderingsystem
I also checked the name a couple of times. fileMenu.exists() returns false.
First, in your root/working directory (in your case it's the folder containing your project), create a folder called 'menus', here you can store all your menus (so you can play around with multi-file input).
Second, move your FastFoodMenu.csv file to that menus folder.
The FastFoodMenu.csv relative path should now look like this: OrderFastFood\menus\FastFoodMenu.csv.
Third, get your working directory from the System properties. This is the folder in which your program is working in. Then, get a reference (File object) to the menus folder.
Lastly, get a reference to the file in question inside the menu folder. When you get to multi-file reading (and at some point, multi-folder reading), you're gonna want to get the files inside the menu folder as a list so that's why I say to just get the menus folder as it's own reference (or just get the file without the isolated reference to the parent aka '\menus\').
So your code should really look like this:
public void getMenu() {
final File workingDir = File(System.getProperty("user.dir"));
final File menusDir = File(workingDir, "menus");
final File fastFoodMenu = File(menusDir, "FastFoodMenu.csv");
try {
final FileInputStream fis = new FileInputStream(fastFoodMenu);
final BufferedInputStream bs = new BufferedInputStream(fis);
while((l = bs.readLine()) != null) {
System.out.println(l);
}
} catch(FileNotFoundException e) {
System.out.println(e.getMessage());
e.printStackTrace()
}
}
This is all psuedocode but that should at least get you started. Make sure to use BufferedInputStream for efficiency, and when reading files, always pass them into FileInputStream's. It's much better than using the Scanner class. I should also mention that when creating a File object, you're not actually creating a file. What you're doing is your're creating an object, giving it the data you want it to have (such as whether it's a folder, and if it is, what child files/folders do you want it to have, whether it's protected or not, hidden or not, etc) before actually telling the system to create the file with everything else.
Your csv file is probably at the wrong place. You're just specifying the file name, which is a relative path.
Relative paths are always resolved against the working directory of your application, not against the directory where your source file(s) are.
To solve the issue, you can
move the files to the real working directory.
use an absolute path (not advisable!)
specify the folder of your data files as program argument or in a config file (in your working directory)
put the files somewhere into the classpath of your application and load them from there via classloader. Note that files that are in your classpath are usually packed with your application and hence not easily modifiable by the user, so this solution doesn't work if the file must be changed by the user.

How to open a file in the same directory as the .jar file of the application? [duplicate]

This question already has answers here:
How to get the real path of Java application at runtime?
(15 answers)
Closed 6 years ago.
I'm trying to load a .txt file into an arrayList in java using a combination of relative paths.
My jar file is in /usr/tool/dist/tool.jar
The file I want to load is in /usr/tool/files/file.txt
I think I was able to retrieve the path of my tool.jar, but how can I go from that path to the one where my file is?
I have the following code
// String path should give me '/usr/tool'
File f = new File(System.getProperty("java.class.path"));
File dir = f.getAbsoluteFile().getParentFile();
String path = dir.toString();
String table1 = this should represent /usr/tool/files/file.txt
BufferedReader buf_table1 = new BufferedReader(new FileReader(new File(table1)));
To find the path of your jar file being executed, java.class.path is not the right property. This property may contain more than one file, and you cannot know which is the right one. (See the docs.)
To find the path of the correct jar file, you can use this instead:
URL url = MainClass.class.getProtectionDomain().getCodeSource().getLocation().getPath();
Where MainClass the main class of your tool, or any other class in the same jar file.
Next, the parent File of a file is its directory. So the parent File of /usr/tool/dist/tool.jar is /usr/tool/dist/. So if you want to get to /usr/tool/files/file.txt, you need to get the parent of the parent, and then from there files/file.txt.
Putting it together:
File jarFile = new File(MainClass.class.getProtectionDomain().getCodeSource().getLocation().getPath());
File file = new File(jarFile.getParentFile().getParent(), "files/file.txt");

Java InputStream fails to read file from within JAR

I am trying to read a file from my executable .jar file but it keeps getting null values.
I have this code:
public DanceEventTicketScanner(String txtfile){
sv = new ScannerView(this);
findcode = false;
InputStream is = this.getClass().getResourceAsStream("/resources/copy.csv");
if (is == null) JOptionPane.showMessageDialog(null, "Resource not located.");
}
In the JAR file i have (as normal) a folder containing all my .class files and in the same directory a folder named resources which holds the copy.csv file.
This code however does not recognize the file.
Does anyone have any ideas?
Remove the first slash:
InputStream is = this.getClass().getResourceAsStream("resources/copy.csv");
getClass().getResourceAsStream(..) will use a path relative to the class (so inc. package dirs). getClass().getClassLoader().getResourceAsStream(..) will use an absolute path. So change your code and get the class loader and it will work.

How to create a new file together with missing parent directories?

When using
file.createNewFile();
I get the following exception
java.io.IOException: Parent directory of file does not exist: /.../pkg/databases/mydb
I am wondering is there a createNewFile that creates the missing parent directories?
Have you tried this?
file.getParentFile().mkdirs();
file.createNewFile();
I don't know of a single method call that will do this, but it's pretty easy as two statements.
As of java7, you can also use NIO2 API:
void createFile() throws IOException {
Path fp = Paths.get("dir1/dir2/newfile.txt");
Files.createDirectories(fp.getParent());
Files.createFile(fp);
}
Jon's answer works if you are certain that the path string with which you are creating a file includes parent directories, i.e. if you are certain that the path is of the form <parent-dir>/<file-name>.
If it does not, i.e. it is a relative path of the form <file-name>, then getParentFile() will return null.
E.g.
File f = new File("dir/text.txt");
f.getParentFile().mkdirs(); // works fine because the path includes a parent directory.
File f = new File("text.txt");
f.getParentFile().mkdirs(); // throws NullPointerException because the parent file is unknown, i.e. `null`.
So if your file path may or may not include parent directories, you are safer with the following code:
File f = new File(filename);
if (f.getParentFile() != null) {
f.getParentFile().mkdirs();
}
f.createNewFile();

Categories