I want to get path after given token "html" which is a fix token and file path is below
String token = "html"
Path path = D:\data\test\html\css\Core.css
Expected Output : css\Core.css
below is input folder for the program. and defined as the constant in the code.
public static final String INPUT_DIR = "D:\data\test\html"
which will contains input html, css, js files. and want to copy these files to different location E:\data\test\html\ here so just need to extract sub path after html from the input file path to append it to the output path.
lets say input file are
D:\data\test\html\css\Core.css
D:\data\test\html\css\Core.html
D:\data\test\html\css\Core.js
so want to extract css\Core.css, css\Core.html, css\Core.js to append it to the destination path E:\data\test\html\ to copy it.
Tried below
String [] array = path.tostring().split("html");
String subpath = array[1];
Output : \css\Core.css
which is not expected output expected output is css\Core.css
Also above code is not working for below path
Path path = D:\data\test\html\bla\bla\html\css\Core.css;
String [] array = path.toString().split("html");
String subpath = array[1];
In this case I am getting something like \bla\bla\ which is not
expected.
If you only need the path in the form of a string another solution would be to use this code:
String path = "D:\\data\\test\\html\\css\\Core.css";
String keyword = "\\html";
System.out.println(path.substring(path.lastIndexOf(keyword) + keyword.length()).trim());
You can replace the path with file.getAbsolutePath() as mentioned above.
import java.io.File;
public class Main {
public static void main(String[] args) {
// Create a File object for the directory that you want to start from
File directory = new File("/path/to/starting/directory");
// Get a list of all files and directories in the directory
File[] files = directory.listFiles();
// Iterate through the list of files and directories
for (File file : files) {
// Check if the file is a directory
if (file.isDirectory()) {
// If it's a directory, recursively search for the file
findFile(file, "target-file.txt");
} else {
// If it's a file, check if it's the target file
if (file.getName().equals("target-file.txt")) {
// If it's the target file, print the file path
System.out.println(file.getAbsolutePath());
}
}
}
}
public static void findFile(File directory, String targetFileName) {
// Get a list of all files and directories in the directory
File[] files = directory.listFiles();
// Iterate through the list of files and directories
for (File file : files) {
// Check if the file is a directory
if (file.isDirectory()) {
// If it's a directory, recursively search for the file
findFile(file, targetFileName);
} else {
// If it's a file, check if it's the target file
if (file.getName().equals(targetFileName)) {
// If it's the target file, print the file path
System.out.println(file.getAbsolutePath());
}
}
}
}
}
This code uses a recursive function to search through all subdirectories of the starting directory and print the file path of the target file (in this case, "target-file.txt") if it is found.
You can modify this code to suit your specific needs, such as changing the starting directory or target file name. You can also modify the code to perform different actions on the target file, such as reading its contents or copying it to another location.
Your question lacks details.
Is the "path" a Path or a String?
How do you determine which part of the "path" you want?
Do you know the entire structure of the "path" or do you just have the delimiting part, for example the html?
Here are six different ways (without iterating, as you stated in your comment). The first two use methods of java.nio.file.Path. The next two use methods of java.lang.String. The last two use regular expressions. Note that there are probably also other ways.
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PathTest {
public static void main(String[] args) {
// D:\data\test\html\css\Core.css
Path path = Paths.get("D:", "data", "test", "html", "css", "Core.css");
System.out.println("Path: " + path);
Path afterHtml = Paths.get("D:", "data", "test", "html").relativize(path);
System.out.println("After 'html': " + afterHtml);
System.out.println("subpath(3): " + path.subpath(3, path.getNameCount()));
String str = path.toString();
System.out.println("replace: " + str.replace("D:\\data\\test\\html\\", ""));
System.out.println("substring: " + str.substring(str.indexOf("html") + 5));
System.out.println("split: " + str.split("\\\\html\\\\")[1]);
Pattern pattern = Pattern.compile("\\\\html\\\\(.*$)");
Matcher matcher = pattern.matcher(str);
if (matcher.find()) {
System.out.println("regex: " + matcher.group(1));
}
}
}
Running the above code produces the following output:
Path: D:\data\test\html\css\Core.css
After 'html': css\Core.css
subpath(3): css\Core.css
replace: css\Core.css
substring: css\Core.css
split: css\Core.css
regex: css\Core.css
I assume you know how to modify the above in order to
I want to get file path after /test
Related
Please consider the following code:
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
public class TestPath {
public static void main(String[] args) {
String filename = "c:/manyOthers/dir1/dir2/dir3";
File f = new File(filename);
String absPathS = f.getAbsolutePath();
System.out.println(absPathS);
// now I try to add a timestamp between dir1 and dir2/dir3 in abstPathS
Path absPath = Paths.get(absPathS);
int n = absPath.getNameCount();
String timestamp = "20210308";
Path subpath = absPath.subpath(0, n-2);
Path outPath = Paths.get(subpath.toString(), timestamp, absPath.subpath(n-2, n).toString());
System.out.println("Timestamped: " + outPath);
}
}
The output is:
c:\manyOthers\dir1\dir2\dir3
Timestamped: manyOthers\dir1\20210308\dir2\dir3
Basically - in my actual code - I receive the absolute path to a folder and I need to insert a subfolder whose name corresponds to a timestamp. The code above is just an example, I am using it here for providing a simple running example; in the actual code the path contains many more subfolders c:/folder1/folder2/.../dir1/dir2/dir3, so, please, if you intend to answer this question, do not tailor the solution to the specific code above.
In the code above, I have the absolute path C:/manyOthers/dir1/dir2/dir3/ and I need to insert a timestamp between dir1 and dir2/dir3. However, as you can see, the problem is that the final output has lost the drive letter.
I have read elsewhere that in Java there are no ways to add back that c:/, but it would be weird ince the prefix c:\ is returned by functions as File.getAbsolutePath(). For example:
File f = new File("any");
System.out.println(f.getAbsolutePath());
prints:
C:\Users\user\workspace\project\any
How I can keep / re-insert the drive letter in my paths?
The problem is that Path.subPath always returns a relative path.
But fortunately your Path absPath is absolute and contains C:\ as the root. So you can get that via absPath.getRoot().
Having this you can create Path outPath from that root:
...
Path outPath = Paths.get(absPath.getRoot().toString(), subpath.toString(), timestamp, absPath.subpath(n-2, n).toString());
...
As #user15244370 commented, the whole thing could be done much more elegant using Path.resolve without using Paths and Path.toString.
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
public class TestPath {
public static void main(String[] args) {
String filename = "c:/manyOthers/dir1/dir2/dir3";
Path absPath = Paths.get(filename);
System.out.println("Source path: " + absPath);
int n = absPath.getNameCount();
String timestamp = "20210308";
Path subpath = absPath.subpath(0, n-2);
Path outPath = absPath.getRoot().resolve(subpath).resolve(timestamp).resolve(absPath.subpath(n-2, n));
System.out.println("Timestamped: " + outPath);
}
}
I use java 1.7 and want to find every folder with a name beginning with "modRepart" in a given path. I 've found code to find files but not to find folders. I also find java 1.8 code that I can't use.
I would suggest something like that:
private static void findFolders(File[] files, String fileName, List<File> foundFiles) {
for (File child : files) {
if (child.isDirectory()) {
if (child.getName().startsWith(fileName)) {
foundFiles.add(child);
}
findFolders(child.listFiles(), fileName, foundFiles);
}
}
}
You could modify this existing answer, and just add in a startsWith clause:
File file = new File("C:\\path\\to\\wherever\\");
String[] names = file.list();
for (String name : names) {
if (new File(file + "\\" + name).isDirectory() && name.startsWith("modRepart")) {
System.out.println(name);
}
}
I have the code below to find the List of files in a specified directory that have a particular word .
isWordPresent(word,filepath) method will give whether the word is contained in the path defined.
The code works absolutely fine until we have some folders inside the local drives.
Eg: String directoryName="D://FOLDER1"
I am not able to do the same , however, with local drives. All combinations of the following gace NullPointerException at //Code line C (as shown in the code snippet).
- String directoryName= "*D://*" OR String Directorypath = "*D:/*"
- String directoryName= "*D:\\*" OR String directoryName= "*D:\*"
( "D:\" would need an escape character, however, I have tried all combinations )
IMportantly, i tried replacing the code line A to:
`File[] roots = File.listRoots(); //code line A
if(Arrays.asList(roots).toString().contains(directoryName)){ //code line B`
where String directoryName = "C:\" and accordingly closed brackets.
The above changes worked until //Code line C where it showed NullpointerException
Is there a way i can access the D Drive?
`public void listFilesHavingTheWord(String directoryName,String word)
throws IOException{
File directory = new File(directoryName);
//get all the files from a directory
File[] fList = directory.listFiles(); //code line A
//code line B
for (File file : fList){ //code line C
if (file.isFile()){
String filepath=file.getAbsolutePath();
if(isWordPresent(word,filepath)){
int index=file.getName().lastIndexOf(".");
if (index > 0) {
String fileNameWithoutExt = file.getName().substring(0, index);
System.out.println("word \""+word+"\" present in file--> "+fileNameWithoutExt);
}
}
} else if (file.isDirectory()){
listFilesHavingTheWord(file.getAbsolutePath(),word);
}
}
}`
When creating a new File object using
File directory = new File(directoryName);
directoryName needs to be a valid name. If it isn't directory.listFiles() returns null and you get the NPE on line C.
In your question you said you tried "*D://*" and various other variants all with wildcard characters (*) in them. This is not a valid file/directory name.
You need to provide a valid directoryName (without wildcards). So using just directoryName = "D:\\"; should work.
instead of providing manually you can use below code for all drive
File[] roots = File.listRoots();
for(int i = 0; i < roots.length ; i++){
System.out.println("drive: " + roots[i]);
//call listFilesHavingTheWord method here
}
and call listFilesHavingTheWord method here and pass parameter;
in this for loop, it will ist all drive one by one
assuming that we have a folder with path:
path="C:\\Users\\me\\Desktop\\here"
also, consider a File[] named readFrom has different files. as an example, consider following path which refering to a file:
C:\\Users\\me\\Desktop\\files\\1\\sample.txt"
my question is, how can i have a string with following value:
String writeHere= "C:\\Users\\me\\Desktop\\here\\files\\1\\sample.txt"
EDIT
I should have mentioned that this path is unknown, we need first to read a file and get its path then write it into another folder, so for the path of writing I need writeHere as input. in conclusion , the answer should contains the way to get the path from the file too.
String s1="C:\\Users\\me\\Desktop\\here";
String s2="C:\\Users\\me\\Desktop\\files\\1\\sample.txt";
String s3=s2.substring(s2.indexOf("\\files"));
System.out.println(s1+s3);
OUTPUT
C:\Users\me\Desktop\here\files\1\sample.txt
To get Absolute Path of file
File f=new File("C:\\Users\\me\\Desktop\\files\\1\\sample.txt");
System.out.println(f.getAbsolutePath());
Split the into arrays and merge the path with split-ted string
String path="C:\\Users\\me\\Desktop\\here";
String [] splt = yourPath.split("\\");
finalPath = path + "\\" + splt[3] + "\\" + splt[4] + "\\" + splt[5];
yourPath is the path refering to a file
Changing the folder's path
File afile =new File("C:\\Users\\me\\Desktop\\files\\1\\sample.txt");
afile.renameTo(new File(finalPath))
If you just need the String and do not need to read the file, use string concatenation with is just str1 + str2. If you need the File object create a base File object on the initial path and then two new File objects from that:
File path = new File("C:\\Users\\me\\Desktop\\here");
String[] files = { "files\\1\\sample.txt", "files\\3\\this.avi" };
for (filename in files) {
File f = new File(path, filename);
...
}
Oh, I think I see better what you want to do. You want to "reparent" the files:
// Note:
// newParent I assume would be a parameter, not hardcoded
// If so, there is no hardcoding of the platform specific path delimiter
// the value, start, is also assumed to be a parameter
File newParent = new File("C:\\Users\\me\\Desktop\\here");
File[] readFrom = ...;
for (File f in readFrom) {
String[] parts = f.list();
String[] needed = Arrays.copyOfRange(parts, start, parts.length);
File newFile = new File(newParent);
for (String part in needed) {
newFile = new File(newFile, part);
}
...
}
I think you could do something like:
String name = "Rafael";
String lastname = " Nunes";
String fullname = name + lastname;
Here you can see the string concatenation working, and you can often visit the Java documentation.
I wrote some code to read a text file from C drive directly given a path.
String fileName1 = "c:\\M2011001582.TXT";
BufferedReader is = new BufferedReader(new FileReader(fileName1));
I want to get a list of files whose filename starts with M. How can I achieve this?
"but how can i write a code that file is exist in local drive or not"
To scan a directory for files matching a condition:
import java.io.File;
import java.io.FilenameFilter;
public class DirScan
{
public static void main(String[] args)
{
File root = new File("C:\\");
FilenameFilter beginswithm = new FilenameFilter()
{
public boolean accept(File directory, String filename) {
return filename.startsWith("M");
}
};
File[] files = root.listFiles(beginswithm);
for (File f: files)
{
System.out.println(f);
}
}
}
(The files will exist, otherwise they wouldn't be found).
You can split the string based on the token '\' and take the second element in the array and check it by using the startsWith() method avaialble on the String object
String splitString = fileName1.split("\\") ;
//check if splitString is not null and size is greater than 1 and then do the following
if(splitString[1].startsWith("M")){
// do whatever you want
}
To check if file exist, you can check in File Class docs
In Nutshell:
File f = new File(fileName1);
if(f.exists()) {
//do something
}