Let' say I have two paths, first can look like folder/ and second like /anotherFolder/image.png. I would like to merge those two paths in some automated fashion and with option for user to omit the last slash in first string and first slash in second string. So all of these
folder/ + /anotherFolder/image.png
folder + anotherFolder/image.png
folder + /anotherFolder/image.png
should give me folder/anotherFolder/image.png
I need to merge two properties in one of my projects and I want it as dummy as possible:)So is there some trick with URL class or do I have to play around with Strings?
You can do this with java.io.File, by using the constructor which takes a File and a String as arguments, will interpret the String as a relative path to the File.
Or with java.net.URL, you can send an URL and a String to the constructur, which will interpret the URL as a context for the String parameter.
I actually used FileUtils.getFile() from Apache Commons IO but Rolf's solution was working too.
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."))
With the following properties file:
foo=hello, world!
bar=first,second
I would like to retrieve the first item as a string and the second as an array. I would have thought that getString vs getStringArray would deal with this, but it doesn't - getString("foo") just gets everything before the comma, i.e. "hello".
If I disable delimiter parsing using setDelimiterParsingDisabled, foo is fine, but this also changes the behaviour of getStringArray("bar") to return a single-element array!
I can't find how I can explicitly tell it how I want it to interpret an individual config item, either as a string or as an array. I don't want to put the config items into separate config files with different delimiter rules, and I'd prefer to use a comma as the delimiter for the getStringArray case.
To elaborate, this snippet prints either hello - 2 or hello, world! - 1 - I want it to print hello, world! - 2 !
AbstractFileConfiguration config = new PropertiesConfiguration();
config.setFileName("C:\\temp\\temp.properties");
//config.setDelimiterParsingDisabled(true);
config.load();
System.out.println(config.getString("foo") + " - " + config.getStringArray("bar").length);
As you found out, Commons Config lacks something like a getPlainString() method. Here are some suggestions for workarounds.
I think using a different list delimiter is the easiest to implement. If you need something more complex, consider the other two:
Use a different list delimiter with setListDelimiter()
Works as long as you don't need to interpret the same value as a String and as an array.
properties file:
foo=hello, world!
bar=first;second
Code:
AbstractFileConfiguration config = new PropertiesConfiguration();
config.setFileName("C:\\temp\\temp.properties");
config.setListDelimiter(';');
config.load();
System.out.println(config.getString("foo") + " - " + config.getStringArray("bar").length);
Disable delimiter parsing and do your own splitting
Easily done with String.split(). A simple static method will do:
public static String[] gerStringArray(Configuration config, String key)
Or create a subclass of PropertiesConfiguration and override the getStringArray() and getList() methods.
Use two different configurations
One for settings data where you know what format the data will have. Here you can activate delimiter parsing.
And one for text data where you might have arbitrary data. Here you should deactivate delimiter parsing.
This has the additional advantage of separating settings and text data.
Not mixing settings and text data keeps both configurations cleaner. Especially if there's a lot of both.
Often settings data changes depending on the deployment environment (live/test) while text data changes depending on the locale (en_GB/de_DE).
In the properties file you can do something like that:
urls=localhost
urls=127.0.0.1
In Java you can get the list:
String[] urls = Configure.settings().getStringArray("urls");
for(String url : urls)
System.out.println(url);
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]
^.*\\(.*?)\..*?$
I was wondering if there is any nice solution for the following problem:
Assuming I have a string with the absolute Path to a file and the file has the prefix "temp_".
I am able to trim the prefix with string.replaceFirst().
But if I am unlucky "temp_" is also part of the directory in that String.
How to make sure only the last occurence will get trimmed?
I can only think to parse it myself, but was wondering if there's magic left to do it a better way?
To be more precisely as example:
C:\Dump\sol1\temp_results\temp_2012-04-core.pcap
Should become:
C:\Dump\sol1\temp_results\2012-04-core.pcap
If you use Path.getFileName(), only the base name of the file is returned (ie, it does not include any parent directory). You can do your substitution with that and put it back together using other Path functions (see getName(), subpath(), etc) into either another Path or a single String.
if you have got it is a File id defo use #goldilocks' approach. But if for some reason you simply have it as a String, first thing that popped into my head is this:
String target = "temp_";
String fullPath = "C:/Dump/sol1/temp_results/temp_2012-04-core.pcap";
StringBuffer sb = new StringBuffer(fullPath);
int end = fullPath.lastIndexOf(target) + target.length();
System.out.println(sb.replace(fullPath.lastIndexOf(target), end, ""));
This is just another example How to do it.
devide total String into three parts.
1.substring till temp_ last occurence
2.last occuerence of temp_
3.substring after last occuerence of temp_
cancat 1+3 anyway I recommend #goldilocks solution
If I have a directory called temp with the following files:
a_file1.jpg
a_file2.jpg
b_file1.jpg
b_file2.jpg
It's possible to get all files like this:
VFS.getManager().resolveFile("temp").getChildren();
But, what I actually want to do is get a_file1.jpg and a_file2.jpg. Maybe like:
VFS.getManager().resolveFile("temp/a*").getChildren();
But this throws an exception:
org.apache.commons.vfs.FileSystemException: Could not list the contents of "temp/a*" because it is not a folder.
So, does anyone know how to resolve a set of files based on a regex with VFS?
You could use the findFiles method, with a FileFilterSelector.
You'll need to create your own FileFilter that accepts the files that match your desired regex.