Name: bsC130419 Date: 06/05/2001
java version "1.4.0-beta"
Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.0-beta-b65)
Java HotSpot(TM) Client VM (build 1.4.0-beta-b65, mixed mode)
Prior to jdk1.4 beta (build 1.4.0-beta-b65), getClass().getResource
("myfile").getFile() would return the location of "myfile" which then could be
used to read "myfile". For e.g. it would return /C:/Documents and
Settings/myfile
But in jdk1.4 beta (build 1.4.0-beta-b65) getClass().getResource
("myfile").getFile() returns the location of myfile that has spaces translated
into %20 characters. So, now it returns something like /C:/Documents%20and%
20Settings/myfile This cannot be used as a valid file name in java.io.File,
or java.io.FileInputStream classes
Existing code that uses getClass().getResource("myfile").getFile() does not
work in jdk1.4 beta (build 1.4.0-beta-b65).
------------------------------------------------------------------
import java.net.*;
import java.io.*;
public class GetClassGetResourceGetFileNameBug {
public void testReadingFileWithCustomBuffering() {
try {
URL url = getClass().getResource("webster-
dictionary.txt");
String fileName = url.getFile();
System.out.println("File name of the resource "+
fileName);
FileInputStream fis = new FileInputStream(fileName);
byte buf[] = new byte[2048];
int cnt = 0; // number of lines
int n;
while((n = fis.read(buf)) != -1) {
for(int i = 0; i < n; i++) {
if(buf[i] == '\n') {
cnt++;
}
}
}
fis.close();
System.out.println("\t\t# lines read : " + cnt);
} catch(IOException e) {
System.err.println(e);
}
}
public static void main(String args[]) {
(new GetClassGetResourceGetFileNameBug
()).testReadingFileWithCustomBuffering();
} // end main
} // end class
----------------------------------------------------------
C:\Documents and Settings\akjain\DESKTOP\performance>c:\jdk1.4\bin\java -cp . Ge
tClassGetResourceGetFileNameBug
File name of the resource /C:/Documents%20and%20Settings/akjain/DESKTOP/performa
nce/webster-dictionary.txt
java.io.FileNotFoundException: /C:/Documents%20and%20Settings/akjain/DESKTOP/per
formance/webster-dictionary.txt (The system cannot find the path specified)
---------------------------------------------------
To run this program you will have to put (any text file/fake) "webster-
dictionary.txt" file in the directory where your java class is located.
-----------------------------------------------------------
(Review ID: 125856)
======================================================================
- duplicates
-
JDK-4639610 REGRESSION: new File(java.net.URL.getFile()) failed when directory has spaces
-
- Closed
-