Java File URI error?
I need to get a file object online, and I know the file is located at : http://nmjava.com/Dir_App_IDs/Dir_GlassPaneDemo/GlassPaneDemo_2010_04_06_15_00_SNGRGLJAMX
If I paste it into my browser's url, I'll be able to download this file, now I'm trying to get it with Java, my code looks like this :
String File_Url="http://nmjava.com/Dir_App_IDs/Dir_GlassPaneDemo/GlassP开发者_JS百科aneDemo_2010_04_06_15_00_SNGRGLJAMX";
Object myObject=Get_Online_File(new URI(File_Url));
Object Get_Online_File(URI File_Uri) throws IOException
{
return readObject(new ObjectInputStream(new FileInputStream(new File(File_Uri))));
}
public static synchronized Object readObject(ObjectInput in) throws IOException
{
Object o;
......
return o;
}
But I got the following error message :
java.lang.IllegalArgumentException: URI scheme is not "file"
at java.io.File.<init>(File.java:366)
Why ? How to fix it ?
Frank
I'm not sure if FileInputStream is designed for reading over the internet .. try new URL(File_Uri).openConnection().getInputStream()
Don't use FileInputStream for this purpose. Create URL, then get input stream and read data from it.
URL url = new URL (fileUrl);
InputStream inputStream = url.openStream ();
readData (inputStream);
For reading data I recommend you to use Commons IO library (especially if there are 2 or more places where you work with streams, it'll save your time and make your code more expressive):
private byte[] readData (InputStream in) {
try {
return IOUtils.toByteArray (in);
} finally {
IOUtils.closeQuietly(in);
}
}
You also operate in your code with Object streams (like ObjectInputStream). But that stream should be used only to read serialized java object and it's not the case as I understand from the description (if it would be a serialized object then your browser hadn't opened that file).
I got inspired, the correct answer is :
Object myObject=Get_Online_File(new URL(File_Url));
Object Get_Online_File(URL File_Url) throws IOException
{
return readObject(new ObjectInputStream(File_Url.openConnection().getInputStream()));
// or readObject(new ObjectInputStream(File_Url.openStream()));
}
Try "file://nmjava.com/Dir_App_IDs/Dir_GlassPaneDemo/GlassPaneDemo_2010_04_06_15_00_SNGRGLJAMX"
精彩评论