Java Wild card to search for directory - java

I need to search for a folder which changes for different environments. Although the file name remains constant , the folder name is changed.
In the below screenshot , branch-name changes for the environment; Config and the log file remains the same.
I want to use wild card to search for the config inside the branch-name folder. I used the following , but that doesnt seem to work and returns an error message saying path not found.
String LOCAL_DIR = "*/config/";
What should be done in order to search for the branch-name folder without passing it as the name is changed across various environments ?
Thanks in advance.

If you are fine using a library, we can do a recursive search in a root folder that you can mention and achieve this by searching for files having .log as extension
Maven:
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.9.0</version>
</dependency>
Sample Code:
import java.io.File;
import java.util.Collection;
import org.apache.commons.io.FileUtils;
public class Test {
public static void main(String[] args) {
//mention the file suffix
String[] SUFFIX = {"log"};
//mention your root directory here to do a recursive search
String root_dir = "C:\\work";
Collection<File> files = FileUtils.listFiles(new File(root_dir), SUFFIX, true);
for(File file: files) {
if(file.getAbsolutePath().contains("/config/") //this will be good for unix/linux
|| file.getAbsolutePath().contains("\\config\\") //this will be good for windows
) {
//this is your required file meeting all the criteria
System.out.println(file.getAbsolutePath());
}
}
}
}

Related

Get normalized path for windows location in Java

I have a requirement where I have a path as C:\..\bar
for this the file bar gets created in the C drive when I use this path in SQL server.
Now on using Apache's FilenameUtils, The normalize method returns null as also documented.
C:\..\bar --> null
But I want
C:\bar for C:\..\bar
Is there any way in Java to get C:\bar for C:\..\bar
I know that .. would mean parent directory but SQL server still creates file the C drive.
The issue with using File or Path classes is that they make use of underlying Filesystem, which in my case is Unix but the path I will get will be windows absolute path.
So basically want to get rid of any redundancy like dots and slashes irrespective of the file system.
You can use getCanonicalFile.
import java.io.File;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
File file = new File("C:\\..\\bar");
System.out.println(file.getCanonicalPath());
}
}

How to read the files inside a directory when Only Relative path of directory is known

In my java application,
1. I have relative path of the directory (Directory and files in it are part of the build).
2.The directory contains multiple files.
3. I want to read the file names in the parent directory.
4. Files can change later and are many in number, So I do not know the names of the files and Do not want my code to change if more files are added or removed or renamed
Now as I do not know the names of the files before hand as they may change later (there are multiple files which can vary according to environment). I only know about the relative path of the parent directory of the files.
How do I read the files ?
You can get list of all files of that directory by file.getlistFiles() method of file class.
It returns an array of files.
Even you can define filter for your files, so it returns exactly files that you want.
try {
File f = new File("D:/Programming");
FilenameFilter filter = new FilenameFilter() {
#Override
public boolean accept(File f, String name) {
// We want to find only .c files
return name.endsWith(".c");
}
};
// Note that this time we are using a File class as an array,
// instead of String
File[] files = f.listFiles(filter);
look at this example.
If you want to use relative path, You can use
System.getProperty("user.dir");
String relative Path =System.getProperty("user.dir");
it returns the folder that you put your app in it.
If your folder has some subfolders, you can simply use file.list();
it returns names of all files and folders of your directory .
String [] listOfMyFilesAndFolders =file.list();
you can add these names to your path to access another folders.
You can check your path is a file or is a folder by using
file.isDirectory();
for ( String path: listOfFilesAndFolders ) {
File file = new File(basePath+path);
if ( file.isDirectory() {
// it is a folder and you can use another for loop or recursion to navigate sub directories
} else {
// it is a file and you can do everyThing you want}}
I think that you can use recursion to walk in your sub directories use recursion to read more
I hope helps.
the question is badly asked and the text is misleading.
"I have relative path of the directory (Directory and files in it are part of the build)" means little and nothing, you have to clarify what you mean.
Assuming you get a relative directory (for example "/folder1/folder2") via command line parameter, you basically have 3 choices:
1) start the program with the directory in which the jar is located as the "current directory", so that it can be used as a working directory. This approach requires that when you launch your application via the java -jar myapp.jar command first you prepend a "cd" command to place yourself directly in the directory. The code will look like the #hamidreza75 solution but obviously you will not have the variable "D: / Programming" but directly the relative path of the directory in which to read the files.
launch script
#echo off
cd {jar-folder}
java -jar myapp.jar
java code:
package com.sample.stack;
import java.io.File;
import java.io.FilenameFilter;
public class FileRenamenter {
public static void main(String[] args) {
final String relativePath = "folder1/folder2";
File directory = new File(relativePath);
String[] list = directory.list(new FilenameFilter(){
public boolean accept(File dir, String name) {
// filter condition
return true;
}
});
// echo file list
for (String filePath : list) {
System.out.println(filePath);
}
}
}
2) pass the folder to be controlled via command line parameter, like this:
launch script
#echo off
java -jar {jar-folder}/myapp.jar {jar-folder}
java code (only the "directory" variable changes)
File directory = new File(args[0], relativePath); // note args[0]
3) programmatically find the folder in which the jar is running [very discouraged practice] and then concatenate the relative path:
java code (only the "directory" variable changes):
String jarFolder = ClassLoader.getSystemClassLoader().getResource(".").getPath();
File directory = new File(jarFolder, relativePath); // note jarFolder

Error trying to read from a text file [duplicate]

I have a file named "word.txt".
It is in the same directory as my java file.
But when I try to access it in the following code this file not found error occurs:
Exception in thread "main" java.io.FileNotFoundException: word.txt
(The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(Unknown Source)
at java.util.Scanner.<init>(Unknown Source)
at Hangman1.main(Hangman1.java:6)
Here's my code:
import java.io.File;
import java.util.*;
public class Hangman1 {
public static void main(String[] args) throws Exception {
Scanner input = new Scanner(new File("word.txt"));
String in = "";
in = input.nextLine();
}
}
Put the word.txt directly as a child of the project root folder and a peer of src
Project_Root
src
word.txt
Disclaimer: I'd like to explain why this works for this particular case and why it may not work for others.
Why it works:
When you use File or any of the other FileXxx variants, you are looking for a file on the file system relative to the "working directory". The working directory, can be described as this:
When you run from the command line
C:\EclipseWorkspace\ProjectRoot\bin > java com.mypackage.Hangman1
the working directory is C:\EclipseWorkspace\ProjectRoot\bin. With your IDE (at least all the ones I've worked with), the working directory is the ProjectRoot. So when the file is in the ProjectRoot, then using just the file name as the relative path is valid, because it is at the root of the working directory.
Similarly, if this was your project structure ProjectRoot\src\word.txt, then the path "src/word.txt" would be valid.
Why it May not Work
For one, the working directory could always change. For instance, running the code from the command line like in the example above, the working directory is the bin. So in this case it will fail, as there is not bin\word.txt
Secondly, if you were to export this project into a jar, and the file was configured to be included in the jar, it would also fail, as the path will no longer be valid either.
That being said, you need to determine if the file is to be an embedded-resource (or just "resource" - terms which sometimes I'll use interchangeably). If so, then you will want to build the file into the classpath, and access it via an URL. First thing you would need to do (in this particular) case is make sure that the file get built into the classpath. With the file in the project root, you must configure the build to include the file. But if you put the file in the src or in some directory below, then the default build should put it into the class path.
You can access classpath resource in a number of ways. You can make use of the Class class, which has getResourceXxx method, from which you use to obtain classpath resources.
For example, if you changed your project structure to ProjectRoot\src\resources\word.txt, you could use this:
InputStream is = Hangman1.class.getResourceAsStream("/resources/word.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
getResourceAsStream returns an InputStream, but obtains an URL under the hood. Alternatively, you could get an URL if that's what you need. getResource() will return an URL
For Maven users, where the directory structure is like src/main/resources, the contents of the resources folder is put at the root of the classpath. So if you have a file in there, then you would only use getResourceAsStream("/thefile.txt")
Relative paths can be used, but they can be tricky. The best solution is to know where your files are being saved, that is, print the folder:
import java.io.File;
import java.util.*;
public class Hangman1 {
public static void main(String[] args) throws Exception {
File myFile = new File("word.txt");
System.out.println("Attempting to read from file in: "+myFile.getCanonicalPath());
Scanner input = new Scanner(myFile);
String in = "";
in = input.nextLine();
}
}
This code should print the folder where it is looking for. Place the file there and you'll be good to go.
Your file should directly be under the project folder, and not inside any other sub-folder.
If the folder of your project is named for e.g. AProject, it should be in the same place as your src folder.
Aproject
src
word.txt
Try to create a file using the code, so you will get to know the path of the file where the system create
File test=new File("check.txt");
if (test.createNewFile()) {
System.out.println("File created: " + test.getName());
}
I was reading path from a properties file and didn't mention there was a space in the end.
Make sure you don't have one.
Make sure when you create a txt file you don't type in the name "name.txt", just type in "name". If you type "name.txt" Eclipse will see it as "name.txt.txt". This solved it for me. Also save the file in the src folder, not the folder were the .java resides, one folder up.
I have the same problem, but you know why? because I didn't put .txt in the end of my File and so it was File not a textFile, you shoud do just two things:
Put your Text File in the Root Directory (e.x if you have a project called HelloWorld, just right-click on the HelloWorld file in the package Directory and create File
Save as that File with any name that you want but with a .txt in the end of that
I guess your problem is solved, but I write it to other peoples know that.
Thanks.
i think it always boils to the classpath. having said that if you run from the same folder where your .class is then change Scanner input = new Scanner(new File("word.txt")); to Scanner input = new Scanner(new File("./word.txt")); that should work

Why cant I change the the file extension of a desired file in java?

I cant understand why my code refuses to change the file extension of my txt file to java.
Here's my code:
public static void main(String[] arg) {
File file = new File("file.txt"); //File I want to change to .java
File file2 = new File("file.java");
boolean success = file.renameTo(file2); //boolean to check if successful
if (success == true)
{
System.out.println("file extension change successful");
}else
{
System.out.println("File extension change failed");
}
}// main
It always prints "file extension failed" each time and I honestly do not understand why. I'm starting to suspect it might be the permissions on my computer. The compiler I use is Eclipse.
FIXED:
THE CAUSE OF THE PROBLEM:
I had placed the file I wanted to change, file.txt, in the package folder inside my project folder. C:\Users\Acer\workspace\MyProjectName\src\MyPackageName. As a consequence the file could not be found by the system.
THE SOLUTION:
I simply moved the file, file.txt, into the main project folder; C:\Users\Acer\workspace\MyProjectName and this fixed the problem. When I run my program it returns
file extension change successful
.
Thank you all for your help. I really appreciate it.
The Source file i.e file.txt should exist in the mentioned path (in your case its should be inside the eclipse project folder) and no file with the destination file name i.e file.java should exist in the mentioned path.
After you execute your code it will give file extension change successful and file.txt will be gone, its content will be transferred to the file.java
The classic Java File API is pretty limited in a number of respects. In this case, you are getting no feedback as to why the move is failing.
My recommendation, if you are on Java 7, would be to switch to use the nio file functionality that was added in that version. Not only are you then making use of a newer, more robust API, but you should get better messaging as to why your copy is failing. Here is equivalent code to the code you posted.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class MoveFile {
public static void main(String[] arg) {
Path file = Paths.get("file.txt"); //File I want to change to .java
Path file2 = Paths.get("file.java");
try {
Files.move(file, file2);
System.out.println("file extension change successful");
} catch (IOException e) {
System.out.println("File extension change failed: " + e.getMessage());
e.printStackTrace();
}
}
}
For awareness, Oracle provides a good reference page for converting legacy file code to the nio code.

Java - FilenotfoundException for reading text file

by running this...
File file = new File("Highscores.scr");
i keep getting this error, and i really don't know how to get around it.
the file is currently sitting in my source packages with my .java files.
I can quite easily read the file by specifying the path but i intend to run this on multiple computers so i need the file to be portable with the program.
this question isnt about reading the text file but rather specifying its location without using an absolute path .
ive searched for the answer but the answers i get are just "specify the name" and "specify the absolute path".
id post an image to make it more clear but i dont have the 10 rep to do so :/
how do i do this?
cheers.
The best way to do this is to put it in your classpath then getResource()
package com.sandbox;
import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
public class Sandbox {
public static void main(String[] args) throws URISyntaxException, IOException {
new Sandbox().run();
}
private void run() throws URISyntaxException, IOException {
URL resource = Sandbox.class.getResource("/my.txt");
File file = new File(resource.toURI());
String s = FileUtils.readFileToString(file);
System.out.println(s);
}
}
I'm doing this because I'm assuming you need a File. But if you have an api which takes an InputStream instead, it's probably better to use getResourceAsStream instead.
Notice the path, /my.txt. That means, "get a file named my.txt that is in the root directory of the classpath". I'm sure you can read more about getResource and getResourceAsStream to learn more about how to do this. But the key thing here is that the classpath for the file will be the same for any computer you give the executable to (as long as you don't move the file around in your classpath).
BTW, if you get a null pointer exception on the line that does new File, that means that you haven't specified the correct classpath for the file.
As far as I remember the default directory with be the same as your project folder level. Put the file one level higher.
-Project/
----src/
----test/
-Highscores.scr
If you are building your code on your eclipse then you need to put your Highscores.scr to your project folder. Try that and check.
You can try to run the following sample program to check which is the current directory your program is picking up.
File f = new File(".");
System.out.println("Current Directory is: " + f.getAbsolutePath());

Categories