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."))
Related
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
I'm using the template engine StringTemplate for some templates (obviously).
What I want is to be able to store the templates I have in seperate files, ofcourse I can do that with simple .txt files and reading them into a String, looks a bit like this then
ST template = new ST(readTemplateFromFile("template.txt"))
private String readTemplateFromFile(String templateFile){
//read template from file
}
But what I was wondering is if there's functionality in the StringTemplate engine to do that automatically. SO that i don't have to write code that already exists.
I've read something about Group Files but I don't quite understand that,are those like Template files? Or am I completely missing something?
Yes, there is functionality available that can be used directly without providing your own file loading code.
From the ST JavaDoc:
To use templates, you create one (usually via STGroup) and then inject attributes using add(java.lang.String, java.lang.Object). To render its attacks, use render().
To follow that advice the following code can be used.
First, create a file called exampleTemplate.stg and place it on your classpath.
templateExample(param) ::= <<
This is a template with the following param: (<param>)
>>
Then, render the template by using the following code:
// Load the file
final STGroup stGroup = new STGroupFile("exampleTemplate.stg");
// Pick the correct template
final ST templateExample = stGroup.getInstanceOf("templateExample");
// Pass on values to use when rendering
templateExample.add("param", "Hello World");
// Render
final String render = templateExample.render();
// Print
System.out.println(render);
The output is:
This is a template with the following param: (Hello World)
Some additional notes:
STGroupFile is a subclass of STGroup. There are other subclasses as well that you find out more about in the JavaDoc.
In the example above the template file was placed on the classpath. This is not a requirement, files can be placed in a relative folder or a in an absolute folder as well.
How do you merge two .odt files? Doing that by hand, opening each file and copying the content would work, but is unfeasable.
I have tried odttoolkit Simple API (simple-odf-0.8.1-incubating) to achieve that task, creating an empty TextDocument and merging everything into it:
private File masterFile = new File(...);
...
TextDocument t = TextDocument.newTextDocument();
t.save(masterFile);
...
for(File f : filesToMerge){
joinOdt(f);
}
...
void joinOdt(File joinee){
TextDocument master = (TextDocument) TextDocument.loadDocument(masterFile);
TextDocument slave = (TextDocument) TextDocument.loadDocument(joinee);
master.insertContentFromDocumentAfter(slave, master.getParagraphByReverseIndex(0, false), true);
master.save(masterFile);
}
And that works reasonably well, however it looses information about fonts - original files are a combination of Arial Narrow and Windings (for check boxes), output masterFile is all in TimesNewRoman. At first I suspected last parameter of insertContentFromDocumentAfter, but changing it to false breaks (almost) all formatting. Am I doing something wrong? Is there any other way?
I think this is "works as designed".
I tried this once with a global document, which imports documents and display them as is... as long as paragraph styles have different names !
Using same named templates are overwritten with the values the "master" document have.
So I ended up cloning standard styles with unique (per document) names.
HTH
Ma case was a rather simple one, files I wanted to merge were generated the same way and used the same basic formatting. Therefore, starting off of one of my files, instead of an empty document fixed my problem.
However this question will remain open until someone comes up with a more general solution to formatting retention (possibly based on ngulams answer and comments?).
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 am working with files (reading, writing and copying) in my Java application, java.io.File and commons-io were perfect for this kind of tasks.
Right now, I can link to HTML in this way:
Z:\an absolute\path\to\a\file.html
But, I need to provide support for anchors too:
Z:\an absolute\path\to\a\file.html#anchor
keeping the system-independence obtained by using java.io.File. So, I will need to extract the path and the anchor, I wonder whether it will be as easy as searching for a sharp occurrence.
java.io.File includes a constructor that accepts a URI, which can represent all kinds of resources, included URLs and local files (see the rfc). URI's also meets your requirements of supporting anchors, and extracting path information (through instance.getPath()).
File f = new File("Z:\\path\\to\\a\\file.html#anchor");
String anchor = f.toURL().getRef(); //note: toURL is deprecated
If you look at the java source you will see that it is as simple as:
String file = "Z:\\path\\to\\a\\file.html#anchor";
int ind = file.indexOf('#');
String anchor = ind < 0 ? null: file.substring(ind + 1);