How would I go about converting an abstract File path (of File type) into a String type?
File.getPath() will give you the path as a String.
If you want the contents of the file, use either of
IOUtils.toString(InputStream,Charset) from Apache Commons-IO
Files.toString(File,Charset) from Google Guava.
Use File.getAbsolutePath().
check this link Abstarct path to String as path
check the method getPath()
The simplest way to get file path as a string is as below code:
String FilepathAsString = fileobject.getAbsolutePath();
Import required : java.io.File;
If you want to load the contents of the file into a String, using google guava it's a case of
String st = Files.toString(file, Charsets.UTF-8);
see the Javadoc.
Of course this does require you to know the character set of the file. Files contain bytes, strings are characters, and there always end up being bugs when converting between the two if you don't actually know what the bytes in your file mean.
Related
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.
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 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.
I have a static method that creates an xml file and I would like it to return the raw xml file as a string. After creating the xml file I would like to read from the file and convert it to a string. How do I go about doing so?
http://guava-libraries.googlecode.com/svn/trunk/javadoc/com/google/common/io/Files.html
Joiner.on('').join(Files.readLines(file, CharSet.fromName("UTF-8")))
you could turn to, for the file handling, to the apache.commons.io library.
This one has build in convenience functions for reading and storing files.
So for reading
org.apache.commons.io.FileUtils#readFileToString(File file)
and for writing
org.apache.commons.io.FileUtils#writeStringToFile(File file, String data)
See here for javadoc
http://commons.apache.org/io/
Here is a variety of ways of doing it:
How to create a Java String from the contents of a file
i have different format files in DB. i want to copy to my local machine.
how can i identify the file format (doc, xls, etc...)
Regards,
krishna
Thanks, for providing suggestions... based on your suggestions i had written the code & i am completed...
please look into my blog.. i posted the code over here...
http://muralie39.wordpress.com/java-program-to-copy-files-from-oracle-to-localhost/
Thank you guys..
Thanks,
krishna
If your files are named according to convention, you can just parse the filename:
String filename = "yourFileName";
int dotPosition = filename.lastIndexOf(".");
String extension = "";
if (dotPosition != -1) {
extension = filename.substring(dotPosition);
}
System.out.println("The file is of type: " + extension);
That's the simplest approach, assuming your files are named using some kind of standard naming convention. The extensions could be proprietary to your system, even, as long as they follow a convention this will work.
If you need to actually scan the file to get the format information, you will need to do some more investigation into document formats.
How are the files stored? Do you have filenames with extensions, or just the binary data?
Mime Util has tools to detect format both from extensions and from magic headers, but of course that's never 100%.
You can use the Tika apache library.
As Dmitri pointed out however, you may have incorrect results sometimes if detecting mime type from file headers or file extension.