How can I create a java.nio.file.Path object from a String object in Java 7?
I.e.
String textPath = "c:/dir1/dir2/dir3";
Path path = ?;
where ? is the missing code that uses textPath.
You can just use the Paths class:
Path path = Paths.get(textPath);
... assuming you want to use the default file system, of course.
From the javadocs..http://docs.oracle.com/javase/tutorial/essential/io/pathOps.html
Path p1 = Paths.get("/tmp/foo");
is the same as
Path p4 = FileSystems.getDefault().getPath("/tmp/foo");
Path p3 = Paths.get(URI.create("file:///Users/joe/FileTest.java"));
Path p5 = Paths.get(System.getProperty("user.home"),"logs", "foo.log");
In Windows, creates file C:\joe\logs\foo.log (assuming user home as C:\joe)
In Unix, creates file /u/joe/logs/foo.log (assuming user home as /u/joe)
If possible I would suggest creating the Path directly from the path elements:
Path path = Paths.get("C:", "dir1", "dir2", "dir3");
// if needed
String textPath = path.toString(); // "C:\\dir1\\dir2\\dir3"
Even when the question is regarding Java 7, I think it adds value to know that from Java 11 onward, there is a static method in Path class that allows to do this straight away:
With all the path in one String:
Path.of("/tmp/foo");
With the path broken down in several Strings:
Path.of("/tmp","foo");
Related
Hey what's up everyone?
I have a simple app to display the file size of files selected by users. The problem is that when the file is located within a folder that has spaces in the folder name or special characters like accents (á é ç) the file path uses different symbols and then I can't get the file size.
The folder is: /Users/home/Checking/First Box
This is my code and the output:
var path = url.absoluteString?.stringByReplacingOccurrencesOfString("file://", withString: "", options: nil, range: nil)
var filePath = path
var attr:NSDictionary? = NSFileManager.defaultManager().attributesOfItemAtPath(filePath!, error: nil)
if let _attr = attr {
fileSize = _attr.fileSize();
}
println(fileSize)
println(filePath!)
And the output is nil for the file size and /Users/home/Checking/First%20Box for the file path.
Also if I select a folder with accent on its name like /Users/home/Checking/Café the output for the path will be /Users/home/Checking/Cafe%CC%81
One solution, which is the one I am using using stringByReplacingOccurrencesOfString but this adds a lot of line to the code since there are many characters with accent throughout the languages around the world and I was wondering if there's another more simple way to do this.
Any help will be much appreciated.
The problem is that you are using a wrong (and too complicated) method
to convert a file URL to a path.
Example:
let url = NSURL(fileURLWithPath: "/ä/ö/ü")!
println(url.absoluteString!) // file:///a%CC%88/o%CC%88/u%CC%88
println(url.path!) // /ä/ö/ü
As you see, .absoluteString returns a HTML string with percent escapes,
whereas .path returns the file path. So your code should look like this:
if let filePath = url.path {
println(filePath)
if let attr : NSDictionary = NSFileManager.defaultManager().attributesOfItemAtPath(filePath, error: nil) {
let fileSize = attr.fileSize();
println(fileSize)
// ...
}
}
If I have an arbitrary file sent to me, using Node.js, how can I figure out what language it's in? It could be a PHP file, HTML, HTML with JavaScript inline, JavaScript, C++ and so on. Given that each of these languages is unique, but shares some syntax with other languages.
Are there any packages or concepts available to figure out what programming language a particular file is written in?
You'd need to get the extension of the file. Are you getting this file with the name including the extension or just the raw file? There is no way to tell if you do not either get the file name with the extension or to scan the dir it's uploaded to and grabbing the names of the files, and performing a directory listing task to loop through them all. Node has file system abilities so both options work. You need the file's name with extension saved in a variable or array to perform this. Depending on how you handle this you can build an array of file types by extensions optionally you can try using this node.js mime
Example:
var fileExtenstions = {h : "C/C++ header", php : "PHP file", jar : "Java executeable"};
You can either split the string that contains the files name using split() or indexOf() with substring.
Split Example:
var fileName = "hey.h"; // C/C++/OBJ-C header
var fileParts = fileName.split(".");
// result would be...
// fileParts[0] = "hey";
// fileParts[1] = "h";
Now you can loop the array of extensions to see what it is and return the description of the file you set in the object literal you can use a 2d array and a for loop on the numeric index and check the first index to see it's the extension and return the second index(second index is 1)
indexOf Example:
var fileName = "hey.h";
var delimiter = ".";
var extension = fileName.substring( indexOf( delimiter ), fileName.length );
now loop through the object and compare the value
I am trying to use fs.existsSync to check whether a file exists. When the full filesystem path is entered, it returns successfully. When the path contains an environment variable like ~/foo.bar or $HOME/foo.bar, it fails to find the file.
I have tried all of the methods from the path module to massage the path first, but nothing seems to work. I should note that the filepath is entered by the user either via command line or a JSON file.
I am aware that the environment variables live in process.env, but I was wondering if there is some way to handle this aside from a find/replace for every possible variable.
Environment variables are expanded by the shell. Node's fs methods make filesystem calls directly.
Read the variable you need out of process.env and use path.join to concatenate.
path.join(process.env.HOME, 'foo.bar');
(Keep in mind there is no HOME variable on Windows if you need to be cross-platform; I believe it's USERPROFILE.)
Since you're dealing with user input, you're going to have to parse the path components yourself.
First, normalize the input string and split it into an array.
var p = path.normalize(inputStr).split(path.sep);
If the first element is ~, replace it with the home directory.
if (p[0] == '~') p[0] = process.env.HOME || process.env.USERPROFILE; // Windows
Then loop over each element, and if it starts with $, replace it.
for (var i = 0; i < p.length; i++) {
if (p[i][0] == '$') {
var evar = p[i].substr(1);
if (process.env[evar]) p[i] = process.env[evar];
}
}
And finally, join the path array back together, re-normalizing:
path.join.apply(path, p);
Use process.env.HOME instead? Then use path.join to get the correct path.
fs.existsSync(path.join(process.env.HOME,"foo.bar"));
Can somebody explain me please why FreeImage library is not recognizing my variable as a valid filename for the method Load, I tried the following code:
var fileName = "C:\\images\\myimage.tif";
var dib = FreeImage.Load(FREE_IMAGE_FORMAT.FIF_TIFF, fileName, 0);
And it's not working, the object dib is always empty (the image is not being loaded), but when I tried the following code:
const string fileName = "C:\\images\\myimage.tif";
var dib = FreeImage.Load(FREE_IMAGE_FORMAT.FIF_TIFF, fileName, 0);
The result is successful, the problem is that I need that image path value to be a normal variable (NOT const), because I work with different images each time, and this images could be anything.
How could I solve this issue, or it's a limitation of the library?
Thanks.
The first thing I see, you are setting the first example as a var instead of string. Define your variable as a string.
I would try that, you dont need the const to make it work I don't believe.
string fileName = "C:\\images\\myimage.tif";
I need to get the name of a file from its full path, in vc++. How can I get this? I need only the file name. Can I use Split method to get this? If not how can I get the file name from the full path of the file?
String^ fileName = "C:\\mydir\\myfile.ext";
String^ path = "C:\\mydir\\";
String^ result;
result = Path::GetFileName( fileName );
Console::WriteLine( "GetFileName('{0}') returns '{1}'", fileName, result );
See Path::GetFileName Method
Find the last \ or /1 using one of the standard library string/char * search methods. Then extract the following text. Remember to special case where the / or \ is the last character.
1 The Windows API, for most purposes2 supports both.
1 The exception is when using long paths starting \\?\ to break 260 character limit on paths.
Directory::GetFiles Method (String, String)
Returns the names of files (including their paths) that match the specified search pattern in the specified directory.