I've got a conditional to check if a certain file exists before proceeding (./logs/error.log). If it isn't found I want to create it. However, will
File tmp = new File("logs/error.log");
tmp.createNewFile();
also create logs/ if it doesn't exist?
No.
Use tmp.getParentFile().mkdirs() before you create the file.
File theDir = new File(DirectoryPath);
if (!theDir.exists()) theDir.mkdirs();
File directory = new File(tmp.getParentFile().getAbsolutePath());
directory.mkdirs();
If the directories already exist, nothing will happen, so you don't need any checks.
Java 8 Style
Path path = Paths.get("logs/error.log");
Files.createDirectories(path.getParent());
To write on file
Files.write(path, "Log log".getBytes());
To read
System.out.println(Files.readAllLines(path));
Full example
public class CreateFolderAndWrite {
public static void main(String[] args) {
try {
Path path = Paths.get("logs/error.log");
Files.createDirectories(path.getParent());
Files.write(path, "Log log".getBytes());
System.out.println(Files.readAllLines(path));
} catch (IOException e) {
e.printStackTrace();
}
}
}
StringUtils.touch(/path/filename.ext) will now (>=1.3) also create the directory and file if they don't exist.
No, and if logs does not exist you'll receive java.io.IOException: No such file or directory
Fun fact for android devs: calls the likes of Files.createDirectories() and Paths.get() would work when supporting min api 26.
Related
This piece of code throws a FileNotFoundException, i'm sure the file exists in my working directory, am i doing something wrong?
private void generateInvoiceNumber(){ //uses reads previous invoice number and increments it.
try {
File invoiceFile = new File("./Invoices/invoiceFile.txt");
FileWriter writer = new FileWriter(invoiceFile,false);
Scanner getter = new Scanner(invoiceFile);
this.invoiceNumber = getter.nextInt();
writer.write(++invoiceNumber);
writer.close();
getter.nextInt();
getter.close();
}
catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
My tip:
Print (in your code) the current path location.
Then you can use this path in order to find the exact path you should use in order to access your file.
Maybe you should put more concrete absolute path:
File invoiceFile = Paths.get ("C:","Invoices", "invoiceFile.txt").toFile();
or if you trying to get from current path:
File invoiceFile = Paths.get (".","Invoices", "invoiceFile.txt").toFile();
And you can check your . path:
System.out.println(new File(".").getCanonicalPath());
Which operating system you are using?
It’s better to use paths when you are constructing a path to your file like
File file = Paths.get (".","Invoices", "invoice.txt").toFile();
corrected " symbols and default root "." which is your folder where app started.
I'm trying to create a folder under /usr in linux from a java program. Here's what I've done. I understand that I lack the permission to do so under /usr but what do I need to add?
public void createDirectory (String path)
{
File directory = new File(path);
if (!directory.exists()) {
if (!directory.mkdirs()) {
System.out.println("couldn't create file");
}
}
}
Here the sysout statement gets printed. what needs to be done here? Would greatly appreciate your help and thanks in advance.
mkdirs() is used in case you want to create nested folders.
Try with mkdir() instead:
public void createDirectory (String path)
{
File directory = new File(path);
if (!directory.exists()) {
if (!directory.mkdir()) {
System.out.println("couldn't create file");
}
}
}
Please note that you must provide the full path in order to make it work. Also as #Reimeus mentioned in the comment above, is not a good idea to write or create anything at that level, I would suggest to create it under /home/your_user/
Hi everyone I can't figure out with this problem : this line of code should work
File[] file = (new File(getClass().getResource("resources/images_resultats"))).listFiles();
I want a list of File, these Files are under "images_resultats" under "resources".
It won't work if resources/images_resultats is not in your classpath and/or if it is in a jar file.
Your code is not even correct it should something like:
File[] file = (new File(getClass().getResource("/my/path").toURI())).listFiles();
You can determine what files are in a folder in resources (even if its in a jar) using the FileSystem class.
public static void doSomethingWithResourcesFolder(String inResourcesPath) throws URISyntaxException {
URI uri = ResourcesFolderUts.class.getResource(inResourcesPath).toURI();
try( FileSystem fileSystem = FileSystems.newFileSystem(uri, Collections.emptyMap() ) ){
Path folderRootPath = fileSystem.getPath(inResourcesPath);
Stream<Path> walk = Files.walk(folderRootPath, 1);
walk.forEach(childFileOrFolder -> {
//do something with the childFileOrFolder
});
} catch (IOException e) {
throw new RuntimeException(e);
}
}
inResourcesPath should be something like "/images_resultats"
Note that the childFileOrFolder paths can only be used while the FileSystem remains open, if you try to (for example) return the paths then use them later you've get a file system closed exception.
Change ResourcesFolderUts for one of your own classes
Assuming that resources folder is in classpath, this might work.
String folder = getClass().getResource("images_resultats").getFile();
File[] test = new File(folder).listFiles();
I'm trying to move files using this java code and it can locate the file but not move it, just deletes the directory I'm moving it to.
public void ch() throws Exception{
if (FC.showOpenDialog(null) == JFileChooser.APPROVE_OPTION){
java.io.File file = FC.getSelectedFile();
Scanner input = new Scanner(file);
System.out.println(file);
Path source = Paths.get(file + "");
Path target = Paths.get("C:\\Users\\Marcus\\Desktop\\2");
try {
Files.move(source, target, REPLACE_EXISTING);
} catch (IOException e){
System.out.println("Failed to move the file");
}
}else{
System.out.println("?");
}
}
Add the file name at the end of your destination path, like below:
You could move files with File.ranameTo() method, like this:
file.renameTo(new File("C:\\Users\\Marcus\\Desktop\\2\\"+file.getName()));
In your example:
public void ch() throws Exception{
if (FC.showOpenDialog(null) == JFileChooser.APPROVE_OPTION){
java.io.File file = FC.getSelectedFile();
try {
file.renameTo(new File("C:\\Users\\Marcus\\Desktop\\2\\"+file.getName()));
} catch (Exception e){
System.out.println("Failed to move the file");
}
}else{
System.out.println("?");
}
}
If you want to use Files.move(), your target path should probably be the full path of the target file, not the destination directory where you want to place it.
Path target = Paths.get("C:\\Users\\Marcus\\Desktop\\2\\" + source.getName());
You should use Files.copy() instead of Files.move().
I strongly recommend the use of a third party tool such as Apache Commons IO's FileUtil class for this type of operation.
For example: FileUtil.moveFileToDirectory
Using these types of utilities saves you from many problems you aren't even aware are lurking. Yes, there are limitations to these common utils, but the benefits usually outweigh them in simple cases.
Google Guava is also an option, but I've got less experience there.
Your code is close but there a couple of potential issues. Before I start, I should say that I'm using a Mac (hence the path change), so while this is working for me, there may be some underlying permission issue on your system I can't account for.
1) You aren't using the name of the file you want to move to. You're using the directory you want to move the file to. That's a fair assumption, but you need to make it the fully qualified path and file name.
2) You are creating a Scanner to the to file but not using it. This probably doesn't really matter, but it's best to eliminate unnecessary code.
3) You don't validate the path that was created by getting the Path instance returned from Files.move().
Here is my example code. I tested it and it worked fine. Again, I'm using a Mac, so take that into account.
public void moveFile(){
JFileChooser fc = new JFileChooser("/");
if (fc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION){
File file = fc.getSelectedFile();
System.out.println("Chosen File: " + file.getAbsolutePath());
String newFileName = System.getProperty("user.home")+File.separator+file.getName();
System.out.println("Attempting to move chosen file to destination: " + newFileName);
Path target = Paths.get(newFileName);
try {
Path newPath = Files.move(file.toPath(), target, REPLACE_EXISTING);
System.out.println("Path returned from move: " + newPath);
} catch (IOException e){
// Checked exceptions are evil.
throw new IllegalStateException("Unable to move the file: " + file.getAbsolutePath(),e);
}
}
}
The output from one of the tests:
Chosen File: /Users/dombroco/temp/simpleDbToFileTest1.txt
Attempting to move chosen file to destination: /Users/dombroco/simpleDbToFileTest1.txt
Path returned from move: /Users/dombroco/simpleDbToFileTest1.txt
We need to call file.exists() before file.delete() before we can delete a file E.g.
File file = ...;
if (file.exists()){
file.delete();
}
Currently in all our project we create a static method in some util class to wrap this code. Is there some other way to achieve the same , so that we not need to copy our utils file in every other project.
Starting from Java 7 you can use deleteIfExists that returns a boolean (or throw an Exception) depending on whether a file was deleted or not. This method may not be atomic with respect to other file system operations. Moreover if a file is in use by JVM/other program then on some operating system it will not be able to remove it. Every file can be converted to path via toPath method . E.g.
File file = ...;
boolean result = Files.deleteIfExists(file.toPath()); //surround it in try catch block
file.delete();
if the file doesn't exist, it will return false.
There's also the Java 7 solution, using the new(ish) Path abstraction:
Path fileToDeletePath = Paths.get("fileToDelete_jdk7.txt");
Files.delete(fileToDeletePath);
Hope this helps.
Apache Commons IO's FileUtils offers FileUtils.deleteQuietly:
Deletes a file, never throwing an exception. If file is a directory, delete it and all sub-directories.
The difference between File.delete() and this method are:
A directory to be deleted does not have to be empty.
No exceptions are thrown when a file or directory cannot be deleted.
This offers a one-liner delete call that won't complain if the file fails to be deleted:
FileUtils.deleteQuietly(new File("test.txt"));
I was working on this type of function, maybe this will interests some of you ...
public boolean deleteFile(File file) throws IOException {
if (file != null) {
if (file.isDirectory()) {
File[] files = file.listFiles();
for (File f: files) {
deleteFile(f);
}
}
return Files.deleteIfExists(file.toPath());
}
return false;
}
if you have the file inside a dirrectory called uploads in your project. bellow code can be used.
Path root = Paths.get("uploads");
File existingFile = new File(this.root.resolve("img.png").toUri());
if (existingFile.exists() && existingFile.isFile()) {
existingFile.delete();
}
OR
If it is inside a different directory this solution can be used.
File existingFile = new File("D:\\<path>\\img.png");
if (existingFile.exists() && existingFile.isFile()) {
existingFile.delete();
}
Use the below statement to delete any files:
FileUtils.forceDelete(FilePath);
Note: Use exception handling codes if you want to use.
Use Apache Commons FileUtils.deleteDirectory() or FileUtils.forceDelete() to log exceptions in case of any failures,
or FileUtils.deleteQuietly() if you're not concerned about exceptions thrown.
Generally We create the File object and check if File Exist then delete.
File f1 = new File("answer.txt");
if(f1.exists()) {
f1.delete();
}
OR
File f2 = new File("answer.txt");
f2.deleteOnExit();
If you are uses the Apache Common then below are the option using which you can delete file and directory
File f3 = new File("answer.txt");
FileUtils.deleteDirectory(f3);
This method throws the exception in case of any failure.
OR
File f4 = new File("answer.txt");
FileUtils.deleteQuietly(f4);
This method will not throw any exception.
This is my solution:
File f = new File("file.txt");
if(f.exists() && !f.isDirectory()) {
f.delete();
}
File xx = new File("filename.txt");
if (xx.exists()) {
System.gc();//Added this part
Thread.sleep(2000);////This part gives the Bufferedreaders and the InputStreams time to close Completely
xx.delete();
}