一、报错:
java.nio.file.InvalidPathException: Illegal char <:> at sun.nio.fs.WindowsPathParser.normalize(WindowsPathParser.java:182) at sun.nio.fs.WindowsPathParser.parse(WindowsPathParser.java:153) at sun.nio.fs.WindowsPathParser.parse(WindowsPathParser.java:77) at sun.nio.fs.WindowsPath.parse(WindowsPath.java:94) at sun.nio.fs.WindowsFileSystem.getPath(WindowsFileSystem.java:255) at java.nio.file.Paths.get(Paths.java:84)
二、报错code
String path = Thread.currentThread().getContextClassLoader().getResource("fileName").getFile();
//或者
//Thread.currentThread().getContextClassLoader().getResource("fileName").getPath();
new String(Files.readAllBytes(Paths.get(path)), "utf-8");
原因:windows系统读取的路径,盘符前有根路径"/"符号。
URL url = Thread.currentThread().getContextClassLoader().getResource("fileName"); content = new String(Files.readAllBytes(Paths.get(url.toURI())), "utf-8");
解决思路:获取URL转URI完事,更直接点,getResourceAsStream读取完事。
java.lang.ClassLoader
public InputStream getResourceAsStream(String name) { URL url = getResource(name); try { return url != null ? url.openStream() : null; } catch (IOException e) { return null; } } public URL getResource(String name) { URL url; if (parent != null) { url = parent.getResource(name); } else { url = getBootstrapResource(name); } if (url == null) { url = findResource(name); } return url; }
java.nio.file.Paths
public static Path get(URI uri) { String scheme = uri.getScheme(); if (scheme == null) throw new IllegalArgumentException("Missing scheme"); // check for default provider to avoid loading of installed providers if (scheme.equalsIgnoreCase("file")) return FileSystems.getDefault().provider().getPath(uri); // try to find provider for (FileSystemProvider provider: FileSystemProvider.installedProviders()) { if (provider.getScheme().equalsIgnoreCase(scheme)) { return provider.getPath(uri); } } throw new FileSystemNotFoundException("Provider \"" + scheme + "\" not installed"); } public static Path get(String first, String... more) { return FileSystems.getDefault().getPath(first, more); }
获取resource目录的路径
Thread.currentThread().getContextClassLoader().getResource("").getPath()
Maven获取resources的文件路径、读取resources的文件
原文地址:https://www.cnblogs.com/foolash/p/12180455.html
时间: 2024-11-05 15:14:43