import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class URLTest {
public static void main(String[] args) {
String urlPath = URLTest.class.getResource("/").getPath();
System.out.println(urlPath);
urlPath = URLTest.class.getResource("/").getFile();
System.out.println(urlPath);
urlPath = URLTest.class.getClassLoader().getResource("").getPath();
System.out.println(urlPath);
urlPath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
System.out.println(urlPath);
try {
FileWriter writer = new FileWriter("D:/test.txt");
writer.write("success\n");
writer.flush();
writer.close();
FileReader read = new FileReader("D:/test.txt");
int i = 1;
while((i = read.read())!=-1)
{
System.out.print((char)i);
}
read.close();
/**下面读写报错 **/
read = new FileReader(urlPath);
writer = new FileWriter(urlPath);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
上述获取路径的方式不能被FileReader()和FileWriter()直接应用因为URL对空格、特殊字符(%,#,[]等)以及中文进行了编码处理;
必须以"/"开头来获取路径:URLTest.class.getResource("/").getPath();不用加"/"可以来获取路径:URLTest.class.getClassLoader().getResource("").getPath();
控制台输出如下图所示: