-
June 11th, 2009, 01:18 PM
#1
String Object to Path?
Hey Guys,
I was wondering if its possible to convert a string object into a path?
Thing is I'm letting the user enter the location of a directory within a jtextfield.
I'm going to use getText() to get the user entered text. But then I want to change it to a path so that I can create a new directory in the location the user specified.
I tried reading up on : http://openjdk.java.net/projects/nio...ile/Paths.html
But it doesn't seem to work:
Am I implementing it wrong? :
Path requiredPath = Paths.get(jTextField.getSelectedText());
-
June 11th, 2009, 01:42 PM
#2
Re: String Object to Path?
I wouldn't even mind changing it into a file object if there is that alternative?
-
June 11th, 2009, 02:06 PM
#3
Re: String Object to Path?
Of course you can change it into a File object and create the file/folder if it does not exist. I personally have never used Path objects, only File objects, so I don't know how they behave. Here is an example.
-
June 11th, 2009, 02:14 PM
#4
Re: String Object to Path?
File sessionDir = new File ( LocationTextField.getSelectedText() , jTextField.getText());
where the LocationTextField.getSelectedText() is nothing but a string having the location like C:\Docs\Location
And jTextField.getText() is merely XYZ, the name of the directory.
... when I try to do that, it just ends up creating the directory in the same location as the project's workspace ... and not in the actual location specified by LocationTextField.
-
June 11th, 2009, 03:09 PM
#5
Re: String Object to Path?
I might be wrong, but you are using LocationTextField.getSelectedText() instead of getText(). If there is nothing selected then it will be an empty string, right? So the file/path will be created in the current folder.
-
June 11th, 2009, 03:16 PM
#6
Re: String Object to Path?
whoops sorry ... that was a typo. Thanks for spotting it!
It works now .. .thanks!
-
October 26th, 2017, 05:57 AM
#7
Re: String Object to Path?
If you want to change it to file object as an alternative I would suggest to refer link below with an explanation and example
Directory in java.
Last edited by sidsomashak; July 4th, 2021 at 08:21 AM.
-
November 7th, 2017, 01:47 AM
#8
Re: String Object to Path?
Use a library like Guava or Commons / IO. They have oneliner methods.
Guava:
Files.toString(file, charset);
Commons / IO:
FileUtils.readFileToString(file, charset);
Without such a library, I'd write a helper method, something like this:
public String readFile(File file, Charset charset) throws IOException {
return new String(Files.readAllBytes(file.toPath()), charset);
}
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|