Lets say I have a directory-structure.
/a/b/c/<unknown name>/d/e/f/<files>
for Windows:
C:\a\b\c\<unknown name>\d\e\f<files>
I know a/b/c is always there and also d/e/f/.
I do not know the directory () between them but I know there is only 1.
Is there a way in Java I can name this path without finding out the name of the 1 unknown directory to access ??
Like so?
/a/b/c/*/d/e/f
Yes, it is possible but probably not as straightforward as you think, you'd use the Files.walk method like follows:
Path root = Paths.get("S:\\Coding\\");
String prefix = "A\\AB";
String suffix = "B\\C";
Path searchRoot = root.resolve(prefix);
System.err.println(searchRoot);
List<Path> paths = Files.walk(searchRoot).filter(f -> f.endsWith(suffix)).collect(Collectors.toList());
paths.forEach(System.out::println);
Outputs:
stderr: S:\Coding\A\AB
stdout: S:\Coding\A\AB\ZZZ\B\C
Lets say you have a dockerized app based on a linux distribution.
You can run this unix command: find . -name d/e/f/yourFilename using Process Builder
This will return the complete filepath to your file which will include the unknown portion. And then you can assign it to a String and use in your Java app.
You can hardcode your search method as indicated in other answers. Or, to stay flexible match against patterns. You would need some pattern language to specify your path:
Shells typically use globbing.
Alternatively you could use regexp to distinguish wanted from unwanted files.
Once you have such a pattern matcher, use a tree walking algorithm (traverse the directory structure recursively), match each absolute path name with your pattern. If it matches, perform some action.
Be aware some globbing seems to exist in Java - see Match path string using glob in Java
Related
I am trying to read a file which has name: K2ssal.timestamp.
I want to handle the time stamp part of the file name as wildcard.
How can I achieve this ?
tried * after file name but not working.
var getK2SSal: Iterator[String] = Source.fromFile("C://Users/nrakhad/Desktop/Work/Data stage migration/Input files/K2Ssal.*").getLines()
You can use Files.newDirectoryStream with directory + glob:
import java.nio.file.{Paths, Files}
val yourFile = Files.newDirectoryStream(
Paths.get("/path/to/the/directory"), // where is the file?
"K2Ssal.*" // glob of the file name
).iterator.next // get first match
Misconception on your end: unless the library call is specifically implemented to do so, using a wildcard simply doesn't work like you expect it to.
Meaning: a file system doesn't know about wildcards. It only knows about existing files and folders. The fact that you can put * on certain commands, and that the wildcard is replaced with file names is a property of the tool(s) you are using. And most often, programming APIs that allow you to query the file system do not include that special wild card handling.
In other words: there is no sense in adding that asterisk like that.
You have to step back and write code that actively searches for files itself. Here are some examples for scala.
You can read the directory and filter on files based upon the string.
val l = new File("""C://Users/nrakhad/Desktop/Work/Data stage migration/Input files/""").listFiles
val s = l.filter(_.toString.contains("K2Ssal."))
I am looking to write and read text files to and from (respectively) a directory different from that of my program. When I specify a directory to write to or read from, should I be using forward slashes or backslashes to identify a file path?
Using forward slashes will make it system independent. I'd stick to that for simplicity.
Consider using java.io.File.separator if you ever display the path to the user. You'd rather not surprise those Windows users. They're a jumpy lot.
I've never found it documented anywhere, but the JDK classes let you use slashes regardless of whether you're on Windows or not. (You can see this in the JDK source, where it explicitly converts path separators for you.)
Officially — and certainly in any UI you're doing — you should use the file.separator system property, which is available via System.getProperty(the list of standard system properties is documented in the docs for System.getProperties):
String sep = System.getProperty("file.separator");
...and also via the static fields They're also available as File.separator (and File.separatorChar).
You can also use the various features of the java.io.File class for combining and splitting paths, and/or the various features of the interfaces and classes in java.nio.file.
You could use either.
If you use / then you only need a single slash.
If you use \, you need to use \\. That is, you need to escape it.
You can also use the resolve() method of the java.nio.Path class to add directories / files to the existing path. That avoids the hassle of using forward or backward slashes. You can then get the absolute path by calling the toAbsolutePath() method followed by toString()
SSCCE:
import java.nio.file.Path;
import java.nio.file.Paths;
public class PathSeperator {
public static void main(String[] args) {
// the path seperator for this system
String pathSep = System.getProperty("path.separator");
// my home directory
Path homeDir = Paths.get(System.getProperty("user.home"));
// lets print them
System.out.println("Path Sep: " + pathSep);
System.out.println(homeDir.toAbsolutePath());
// as it turns out, on my linux it is a colon
// and Java is using forward slash internally
// lets add some more directories to the user.home
homeDir = homeDir.resolve("eclipse").resolve("configuration");
System.out.println("Appending more directories using resolve()");
System.out.println(homeDir);
}
}
You should use /
For example C:/User/...
I'm not very sure there is any regex to replace thoese things:
This is a string value read from a xml file saved through Linux machine
<pcs:message schema="models/HL7_2.5.model"/>
and this is the one saved in Windows machine
<pcs:message schema="model\HL7_2.5.model"/>
This is why the file getting an error in eclipse while exported in Linux and imported in Windows or vise versa.
Is there any regex to find and replace the value(slash and back slash) within String? (not XML parsing) based on working OS?
Thanks in advance
str = str.replaceAll("\\\\|/", "\\"+System.getProperty("file.separator"))
Use the "file.separator" system property and base your regexp on that.
http://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html
Also see this: File.separator vs FileSystem.getSeparator() vs System.getProperty("file.separator")?
This should take care of fixing slashes:
String str = xml.replaceAll("\\\\|/", System.getProperty("file.separator"));
I have got a directory listing as a String and I want to retrieve a particular part of the string, the only thing is that as this is a directory it can change in length
I want to retrieve the file name from the string
"C:\projects\Compiler\Compiler\src\JUnit\ExampleTest.java"
"C:\projects\ExampleTest.java"
So in these two cases I want to retrieve just ExampleTest (the filename can also change so i need something like get the text before the first . and after the last \). Is there a way to do this using something like regex or something similar?
Why not use Apache Commons FileNameUtils rather than coding your own regular expressions ? From the doc:
This class defines six components within a filename (example
C:\dev\project\file.txt):
the prefix - C:\
the path - dev\project\
the full path - C:\dev\project\
the name - file.txt
the base name - file
the extension - txt
You're a lot better off using this. It's geared directly towards filenames, dirs etc. and given that it's a commonly used, well-defined component, it'll have been tested extensively and edge cases ironed out etc.
new File(thePath).getName()
or
int pos = thePath.lastIndexOf("\\");
return pos >= 0? thePath.substring(pos+1): thePath;
File file = new File("C:\\projects\\ExampleTest.java");
System.out.println(file.getAbsoluteFile().getName());
Java code
String test = "C:\\projects\\Compiler\\Compiler\\src\\JUnit\\ExampleTest.java";
String arr[] = test.split("\\Q"+"\\");
System.out.println(arr[arr.length-1].split("\\.")[0]);
This is the regex in c# and it works in java :P too.Thanks to Perl.It matches in Group[1]
^.*\\(.*?)\..*?$
Hi, I have a big problem. I'm making a java program and I have to call an exe file in a folder that have whitespace. This program also has 2 arguments that always have whitspace in the path.
Example:
C:\Users\Program File\convert image\convert.exe C:\users\image exe\image.jpeg C:\Users\out put\out.bmp
I have to do this in Windows but i want generalize it for every OS.
My code is:
Runtime run = Runtime.getRuntime();<br/>
String path_current = System.getProperty("user.dir");<br/>
String [] uno = new String[]{"cmd","/c",path_current+"\\\convert\\\convert.exe",path_current+"\\\f.jpeg", path_current+"\\\fr.bmp"};<br/>
Process proc2 = run.exec(uno);<br/>
proc2.waitFor();<br/>
This does not work. I tried removing the String array and inserting a simple String with "\"" before and after the path but that didn't work. How do I resolve this?
you may want to use :
http://commons.apache.org/io/api-1.4/org/apache/commons/io/FilenameUtils.html#separatorsToSystem(java.lang.String)
see also this answer :
Is there a Java utility which will convert a String path to use the correct File separator char?
Remove "cmd" and "/c", and use a single forward slash instead of your triple backslaches.