I am playing a bit with the new Java 7 IO features. Actually I am trying to retrieve all the XML files in a folder. However this throws an exception when the folder does not exist. How can I check if the folder exists using the new IO?
public UpdateHandler(String release) {
log.info("searching for configuration files in folder " + release);
Path releaseFolder = Paths.get(release);
try(DirectoryStream<Path> stream = Files.newDirectoryStream(releaseFolder, "*.xml")){
for (Path entry: stream){
log.info("working on file " + entry.getFileName());
}
}
catch (IOException e){
log.error("error while retrieving update configuration files " + e.getMessage());
}
}
Using java.nio.file.Files:
Path path = ...;
if (Files.exists(path)) {
// ...
}
You can optionally pass this method LinkOption values:
if (Files.exists(path, LinkOption.NOFOLLOW_LINKS)) {
There's also a method notExists:
if (Files.notExists(path)) {
Quite simple:
new File("/Path/To/File/or/Directory").exists();
And if you want to be certain it is a directory:
File f = new File("/Path/To/File/or/Directory");
if (f.exists() && f.isDirectory()) {
...
}
To check if a directory exists with the new IO:
if (Files.isDirectory(Paths.get("directory"))) {
...
}
isDirectory returns true if the file is a directory; false if the file does not exist, is not a directory, or it cannot be determined if the file is a directory or not.
See: documentation.
Generate a file from the string of your folder directory
String path="Folder directory";
File file = new File(path);
and use method exist.
If you want to generate the folder you sould use mkdir()
if (!file.exists()) {
System.out.print("No Folder");
file.mkdir();
System.out.print("Folder created");
}
You need to transform your Path into a File and test for existence:
for(Path entry: stream){
if(entry.toFile().exists()){
log.info("working on file " + entry.getFileName());
}
}
There is no need to separately call the exists() method, as isDirectory() implicitly checks whether the directory exists or not.
import java.io.File;
import java.nio.file.Paths;
public class Test
{
public static void main(String[] args)
{
File file = new File("C:\\Temp");
System.out.println("File Folder Exist" + isFileDirectoryExists(file));
System.out.println("Directory Exists" + isDirectoryExists("C:\\Temp"));
}
public static boolean isFileDirectoryExists(File file)
{
if (file.exists())
{
return true;
}
return false;
}
public static boolean isDirectoryExists(String directoryPath)
{
if (!Paths.get(directoryPath).toFile().isDirectory())
{
return false;
}
return true;
}
}
We can check files and thire Folders.
import java.io.*;
public class fileCheck
{
public static void main(String arg[])
{
File f = new File("C:/AMD");
if (f.exists() && f.isDirectory()) {
System.out.println("Exists");
//if the file is present then it will show the msg
}
else{
System.out.println("NOT Exists");
//if the file is Not present then it will show the msg
}
}
}
File sourceLoc=new File("/a/b/c/folderName");
boolean isFolderExisted=false;
sourceLoc.exists()==true?sourceLoc.isDirectory()==true?isFolderExisted=true:isFolderExisted=false:isFolderExisted=false;
From SonarLint, if you already have the path, use path.toFile().exists() instead of Files.exists for better performance.
The Files.exists method has noticeably poor performance in JDK 8, and can slow an application significantly when used to check files that don't actually exist.
The same goes for Files.notExists, Files.isDirectory and Files.isRegularFile.
Noncompliant Code Example:
Path myPath;
if(java.nio.Files.exists(myPath)) { // Noncompliant
// do something
}
Compliant Solution:
Path myPath;
if(myPath.toFile().exists())) {
// do something
}
Related
I am trying to read. a config from my resources folder in Java project from my deployed code. I am able to read from my local laptop but after deployment as JAR .manifest file, it says path does not exist.
So my Java maven project str: src/main/java/.. and config path as follows:
Java code to read this config where file.exists() always returns false.
Trial 1: When config path is : src/main/resources/config.yaml.
File configPath = new File(Objects.requireNonNull(getClass().getClassLoader().getResource("config.yaml")).getFile());
if (!configPath.exists()) {
Log("ERROR", "Config file does not exist "); // this is printed
}
Trial 2: When config path is src/main/resources/feed/configs/config.yaml.
File dir = new File(Objects.requireNonNull(getClass().getClassLoader().getResource("feed/configs")).getFile());
if (!dir.exists()) {
Log("ERROR", "Config folder does not exist, "ERROR"); // THIS IS PRINTED
return;
}
File[] configFiles = configPath.listFiles(); // NOT EXECUTED AS ABOVE IS RETURNED
Since you have added the maven tag, I am assuming you are using maven.
As the .yaml is inside the resources folder you should be using getResourceAsStream()
/src/main/resources/config.yaml:
first: value1
second: value2
To read the file and its content:
import java.util.Properties;
import java.io.InputStream;
import java.io.IOException;
public class Example {
InputStream inputStream = null;
final Properties properties = new Properties();
public Example() {
try {
inputStream =
this.getClass().getClassLoader().getResourceAsStream("config.yaml");
properties.load(inputStream);
} catch (IOException exception) {
LOG("ERROR", "Config file does not exist ");
} finally {
if (inputStream != null){
try {
inputStream.close();
} catch (Exception e) {
LOG("ERROR", "Failed to close input stream");
}
}
}
}
public printValues(){
LOG("INFO", "First value is: " + properties.getProperty("first"));
}
}
Hi guys I'm trying to find if a specific file is inside the project directory.
File f = new File(System.getProperty("user.dir"));
System.out.println(f);
String archivoLiga="LigaV2";
System.out.println(f.listFiles((dir1, name) -> name.startsWith(archivoLiga) && name.endsWith(".properties")).length == 0);
But this only works if the file is in the "first" level, i want it to find it even if it's inside another folder. Any ideas?
Use Java 8's find() method to recurse subdirectories:
final int MAX_DEPTH = 50; // Max depth of subdirectories to search
Path userDir = Paths.get(System.getProperty("user.dir"));
System.out.println(userDir);
String archivoLiga="LigaV2";
System.out.println(
Files.find(
userDir,
maxDepth,
(path,attr) -> path.getFileName().startsWith(archivoLiga)
&& path.getFileName().endsWith(".properties"))
.findAny()
.isPresent());
Try recursively looking inside subfolders :-
public boolean checkForFile(String dirname,String prefix,String ext){
File dir = new File(dirname);
//System.out.println(dir);
for(File f : dir.listFiles()){
if(f.isFile()){
if(f.getName().startsWith(prefix) && f.getName().endsWith(ext)){
System.out.println(f.getName());
return true;
}
}
else{
//This step starts looking inside subfolder as well
return checkForFile(f.getAbsolutePath(),prefix,ext);
}
}
return true;
}
To check a file inside a folder, You will need to use exists() method of java.io.File like this:
boolean exists = new File("FOLDER_PATH/FILE_NAME").exists();
if (exists) {
System.out.println("File exists inside given folder");
} else {
System.out.println("File does not exists inside given folder");
}
Also possible with FileVisitor:
#Getter #Setter
#RequiredArgsConstructor
public static class SearchVisitor extends SimpleFileVisitor<Path> {
private final String fileToSearch;
private boolean found=false;
#Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if(!file.getFileName().toString().equals(fileToSearch)) return FileVisitResult.CONTINUE;
found=true;
return FileVisitResult.TERMINATE;
}
}
public void test() throws IOException {
SearchVisitor sv = new SearchVisitor("LigaV2");
Files.walkFileTree( Paths.get(System.getProperty("user.dir")), sv);
log.info("found file {}:{}", sv.getFileToSearch(), sv.isFound());
}
Use public boolean isDirectory() in java file API following is the link to oracle documentation. Tests whether the file denoted by this abstract pathname is a directory.
https://docs.oracle.com/javase/7/docs/api/java/io/File.html#isDirectory()
I have a form with that code:
public Form()
{
initComponents();
try
{
File file= new File("avatar.jpg");
BufferedImage image= ImageIO.read(file);
}
catch (IOException ex)
{
System.out.println("Failed to load image");
}
}
The problem is that the code always throws the IOException and enters in the catch block.
So the file isn't read.
I have created the project with Netbeans 7.2, and the directory looks like this:
What's the problem? Maybe the file shouldn't be there but in the father directory? Or what?
Is your image being packaged within your jar? to find this out, extract you jar file like you would an ordinary zip file and check if the image is anywhere there (normally located by jarname\packagename\filename. If so then you'll need to extract your image as a resource using getResourceAsStream().
It would be something like:
public class Test {
private static final String absName = "/yourpackage/yourimage.jpg";
public static void main(String[] args) {
Class c=null;
try {
c = Class.forName("yourpackage.Test");//pkg is the package name in which the resource lies
} catch (Exception ex) {
// This should not happen.
}
InputStream s = c.getResourceAsStream(absName);
// do something with it.
}
public InputStream getResourceAsStream(String name) {
name = resolveName(name);
ClassLoader cl = getClassLoader();
if (cl==null) {
return ClassLoader.getSystemResourceAsStream(name); // A system class.
}
return cl.getResourceAsStream(name);
}
public java.net.URL getResource(String name) {
name = resolveName(name);
ClassLoader cl = getClassLoader();
if (cl==null) {
return ClassLoader.getSystemResource(name); // A system class.
}
return cl.getResource(name);
}
private String resolveName(String name) {
if (name == null) {
return name;
}
if (!name.startsWith("/")) {
Class c = this;
while (c.isArray()) {
c = c.getComponentType();
}
String baseName = c.getName();
int index = baseName.lastIndexOf('.');
if (index != -1) {
name = baseName.substring(0, index).replace('.', '/') + "/" + name;
}
} else {
name = name.substring(1);
}
return name;
}
}
Reference:
Accessing Resources
It looks like you have a namespace of poker.*
It all depends on where the jvm is initialized from.
Where is your main? Is it in /Users/ramy/NetBeansProjects/Poker/src?
Also, I suggest you use getResource() for all of your file loading needs, especially inside jars.
this.getClass().getResource("/resource/buttons1.png")
or
this.getClass().getResourceAsStream("/resource/TX_Jello2.ttf")
You can find out where your programs default path is by doing the following:
System.getProperty("user.dir");
Without seeing the error I would say the most likely cause is it can't find the file. So I suggest you replace "avatar.jpg" in the File constructor with the absolute file path to it. e.g.
File file = new File("INSERT_PATH_TO_FILE/avatar.jpg");
You cannot assume the image will be "there" because the relative path between your .java and the image seems ok.
Accessing a resource depends of your "kind" of project (Web, standalone....). In your case, you can try to get the image from your classpath
final File inputFile = new ClassPathResource("....").getFile();
final BufferedImage inputImg = ImageIO.read(inputFile);
When I run a class with the following code:
public static void main(String[] args)
{
createDuplicateStructure("in", "out");
}
public static void createDuplicateStructure(String path_start, String path_result)
{
File start = new File(path_start);
File result = new File(path_result);
duplicateDirectoryStructure(start, result);
}
public static void duplicateDirectoryStructure(File start_dir, File result_dir)
{
//FileFilter used by listFiles(filter) - to make sure they are dirs
FileFilter dirs_only = new FileFilter()
{
public boolean accept(File file){ return file.isDirectory();}
};
File[] dir_contents = start_dir.listFiles(dirs_only);
for(File dir : dir_contents)
{
File duplicate = new File(result_dir.getPath(), dir.getName());
if(dir.mkdir())
{
duplicateDirectoryStructure(dir, duplicate);
}
else
{
System.out.println("ERROR: Unable to create dir! (" + duplicate.getPath() + ")");
}
}
}
I get this in the console:
Error: Unable to create dir! (out/a)
Error: Unable to create dir! (out/a)
Error: Unable to create dir! (out/a)
The directory "out" is in the same directory as the .jar.
There is a directory "in" which contains "a", "b", and "c" directories (for testing).
Any ideas why this is not working?
Thanks!
You should replace dir.mkdir() with duplicate.mkdir() because dir is the already existing source directory.
dir.mkdir() only returns true the directory was actually created. Try doing
if(dir.mkdir() || dir.exists())
The line
`if(dir.mkdir())`
is trying to create the existing directory structure
if you change it to
if(duplicate.mkdir())
you get another problem where it tries to create the a subdirectory under out which does not exist yet.
So change it to
if(duplicate.mkdirs())
which will create the directory structure, or create the out directory before you start your loop.
enter code hereI wrote the following code which searches a folder directory recursively to find a specific folder.
The program is supposed to do check the folder name and if the folder name is "src", then it should go into that folder to get all the files. Currently the program is getting all the files from all the directories.
public class Main {
public static void main(String[] args) {
File fileObject = new File("C:\\Users\\lizzie\\Documents\\");
recursiveTraversal(fileObject);
}
public static void recursiveTraversal(File fileObject)
{
if (fileObject.isDirectory())
{
File allFiles[] = fileObject.listFiles();
for(File aFile : allFiles){
recursiveTraversal(aFile);
}
}
else if (fileObject.isFile())
{
System.out.println(fileObject.getAbsolutePath());
}
}
}
when I check if a certain folder is a directory, I added the following constraint but that didn't help.
if (fileObject.isDirectory() && fileObject.getName().equals("src"))`
Please let me know what I can do to improve my code. Anything will be appreciated.
Thanks
If you look at your if-else inside recursiveTraversal, you'll see that you're printing anything that isn't a directory, regardless of where it is. Here's a fix:
public class Main {
public static void main(String[] args) {
File fileObject = new File("C:\\Users\\lizzie\\Documents\\");
recursiveSearch(fileObject);
}
public static void recursiveSearch(File fileObject) {
if (fileObject.isDirectory()) {
if (fileObject.getName().equals("src")) {
recursivePrint(fileObject);
} else {
File allFiles[] = fileObject.listFiles();
for(File aFile : allFiles){
recursiveSearch(aFile);
}
}
}
// ignore non-directory objects during search
}
public static void recursivePrint(File fileObject)
{
if (fileObject.isDirectory())
{
File allFiles[] = fileObject.listFiles();
for(File aFile : allFiles){
recursivePrint(aFile);
}
}
else if (fileObject.isFile())
{
System.out.println(fileObject.getAbsolutePath());
}
}
}
This will print all the files recursively of any directory named src.
What you need to do is put the constraint on what's being printed, not what's being traversed. As you've noticed, the traversal is working fine, since it gets all files in all subfolders.
If you want to print only the filenames inside of the "src" directory (not in subdirectories), then you can do...
...
else if (fileObject.isFile() && fileObject.getParent().getName().equals("src")
{
System.out.println(fileObject.getAbsolutePath());
}
...
If you want to print what's in the "src" directory, and all subdirectories, then you'll need to break your algorithm into two parts
find the "src" folder, then
use your current algorithm to print everything in all directories from there and lower
Instead of checking for .equals() on the name, check if the name contains "src" using either fileObject.getName().contains(StringBuffer) or fileObject.getName().indexOf("src") != -1