Storing File Name only in a parameter - java

I have a requirement in which the parameter is coming as file name that upon debugging I have analyzed, as shown below:
private processfile ( string filepath)
{
}
Now this file path can be like:
C:\abc\file1.txt
or
C:\abc\def\file1.txt
or
C:\ghj\ytr\wer\file1.txt
so I have achieved this with as shown below..
String p = new File(filePath).getName();
Now the issue is that upon printing the parameter p upon console it prints
file1.txt
whereever I was tring that only the file name to be stored and not the extension, such as
P should only contain file1 only and no extenstion. please advise.

What vishal_aim said will work and is correct, but in my opinion it is better to use a library because it will be more expressive and will you won't have to fix all the bugs they've already fixed. Therefore, you should use this:
FilenameUtils.getBaseName(yourFile)
Here's what the documentation says:
a/b/c.txt --> c
a.txt --> a
a/b/c --> c
a/b/c/ --> ""
That last case is something that probably didn't occur to any of us here as a possibility, but the library writers already thought of it for us.

there is no inbuilt API to to get file name without extension. But why cant you trancate it programmatically like:
p = p.substring(0, p.lastIndexOf("."));

Related

File wildcard use *

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."))

How to read object properties from ontology using Jena Java API

I have opened my ontology so far and now I want to read all the objects and display their properties:
I have the next code:
// Opening the ontology.
OntModel model = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
model.read("file:C:/Users/Antonio/Desktop/myOntology.owl","OWL");
// Going through the ontology
for (Iterator<OntClass> i = model.listClasses();i.hasNext();){
OntClass cls = i.next();
System.out.print(cls.getLocalName()+": ");
// here I want to show the properties
}
which just shows the name of the classes, but not their properties.
I have been reading the documentation but I don't find anything useful.
Hopefully someone can help me.
Thanks in advance.
I'm not sure why you would want all the properties but you can do that easily. First of all make sure to import Jena's OntProperty import org.apache.jena.ontology.OntProperty;
Then you can simply inside your for loop : cls.listDeclaredProperties().toList()
If you want to access the content of a specific property though you could do it this way :
Check your .owl file for the URI which generally looks something like this "http://example.com/ontology#"
So your Java code is going to look like this : OntProperty nameOfProperty = model.getOntProperty("http://example.com/ontology#nameOfyourProperty");
Then inside your loop you could do for example something like this : cls.getProperty(nameOfProperty).getString()
And by the way before reading your file you might want to put it in a try catch statement. Hope that helped.
The code is printing classes because listClasses() returns classes of the ontology. For printing the object properties of the individuals, you can use OWL API

How to retrieve particular part of string

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]
^.*\\(.*?)\..*?$

Java - How to get the name of a file from the absolute path and remove its file extension?

I have a problem here, I have a String that contains a value of C:\Users\Ewen\AppData\Roaming\MyProgram\Test.txt, and I want to remove the C:\Users\Ewen\AppData\Roaming\MyProgram\ so that only Test is left. So the question is, how can i remove any part of the string.
Thanks for your time! :)
If you're working strictly with file paths, try this
String path = "C:\\Users\\Ewen\\AppData\\Roaming\\MyProgram\\Test.txt";
File f = new File(path);
System.out.println(f.getName()); // Prints "Test.txt"
Thanks but I also want to remove the .txt
OK then, try this
String fName = f.getName();
System.out.println(fName.substring(0, fName.lastIndexOf('.')));
Please see this for more information.
The String class has all the necessary power to deal with this. Methods you may be interested in:
String.split(), String.substring(), String.lastIndexOf()
Those 3, and more, are described here: http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/String.html
Give it some thought, and you'll have it working in no time :).
I recommend using FilenameUtils.getBaseName(String filename). The FilenameUtils class is a part of Apache Commons IO.
According to the documentation, the method "will handle a file in either Unix or Windows format". "The text after the last forward or backslash and before the last dot is returned" as a String object.
String filename = "C:\\Users\\Ewen\\AppData\\Roaming\\MyProgram\\Test.txt";
String baseName = FilenameUtils.getBaseName(filename);
System.out.println(baseName);
The above code prints Test.

Java : Getting a value from a properties file

I'm using the <liferay-ui:message key="username" /> to get some data from my property file in my portlet.
Is there a Java code equivalent for this tag ?
Thank you.
Actually the question title does not go with question content. To read from portlet.properties you have to do as what Jonny said. But on seeing the content of the question, I assume that what you want is the java code equivalent of the tag output that you have mentioned.
liferay-ui:message DOES NOT read the value from portlet.properties file so PortletProps will not work if that is what you are expecting as it is meant to read value only from portlet.properties and not Language.properties.
You should use methods of LanguageUtil class to get the value.
Yes, it's PortletProps.get(String key).
Hope this helps!
~~ EDIT ~~
The above as Sandeep has pointed out isn't the equivalent of what liferay-ui:message does, but it is the method to retrieve values from a portlet.properties file.
As Sandeep has said you should use LanguageUtil to replicate the functionality in Java code.
If you need merely read property from property file you can:
Properties p = new Properties();
p.load(new FileInputStream("file_with.properties"));
String message = p.getProperty("username");

Categories