上代码
public class ResourceDemo {
public static void main(String[] args) throws IOException {
// 创建资源的实例,ApplicationContext的ResourceLoader实现
final ApplicationContext context = new ClassPathXmlApplicationContext();
final File file = File.createTempFile("test", "txt", new File("d:/"));
file.deleteOnExit();// 程序出错终止时删除
// 访问文件
final Resource resource1 = context.getResource("file://" + file.getPath());
displayInfo(resource1);
// 访问类路径
final Resource resource2 = context.getResource("classpath:test.txt");
displayInfo(resource2);
// 访问URL资源
final Resource resource3 = context.getResource("http://www.baidu.com");
displayInfo(resource3);
}
private static void displayInfo(Resource resource) throws IOException {
System.out.println(resource.getClass());
System.out.println(resource.getURL().getContent());
System.out.println();
}
}
问题
访问文件的resource.getURL().getContent()报错:java.net.UnknownHostException : d
解决问题
public class ResourceDemo {
public static void main(String[] args) throws IOException {
// 创建资源的实例,ApplicationContext的ResourceLoader实现
final ApplicationContext context = new ClassPathXmlApplicationContext();
final File file = File.createTempFile("test", "txt", new File("d:/"));
file.deleteOnExit();// 程序出错终止时删除
// 访问文件
final Resource resource1 = context.getResource("file:" + file.getPath());
displayInfo(resource1);
// 访问类路径
final Resource resource2 = context.getResource("classpath:test.txt");
displayInfo(resource2);
// 访问URL资源
final Resource resource3 = context.getResource("http://www.baidu.com");
displayInfo(resource3);
}
private static void displayInfo(Resource resource) throws IOException {
System.out.println(resource.getClass());
System.out.println(resource.getURL().getContent());
System.out.println();
}
}
格式问题:file:// --> file: final Resource resource1 = context.getResource("file:" + file.getPath());
博客围绕Spring开发展开,给出代码后提出问题,即访问文件时resource.getURL().getContent()报错,错误信息为java.net.UnknownHostException : d,随后说明了要解决该问题。

4万+

被折叠的 条评论
为什么被折叠?



