九种方式解读:2022资源文件获取技巧(resources目录)

需积分: 0 0 下载量 91 浏览量 更新于2024-08-03 收藏 311KB PDF 举报
在2022年10月4日的文章中,作者探讨了如何在Java项目开发中有效地从/resources目录获取资源文件的九种方法,这对于理解和管理项目的静态资源至关重要。这篇文章针对AI和人工智能项目中的技术实践,提供了一种实用的工具箱,帮助开发者熟练掌握资源文件的加载和操作。 首先,文章强调了在项目开发中,resources目录通常用于存放静态资源,这些资源会随着项目打包,便于在代码中通过文件读取的方式访问。作者分享了一个通用的打印文件内容的方法,该方法接受一个文件路径作为输入,无论它是以字符串形式还是InputStream形式,并通过BufferedReader逐行读取文件内容。 方式一的核心在于`getResource`和`getPath`方法的使用。`getResource("")`方法返回的是当前类加载器对应的类路径下指定资源(在这个例子中是空字符串,代表根目录)。通过调用`.getPath()`获取文件的实际路径,然后可以组合文件名来构建完整的文件路径,最后通过`getFileContent`方法读取文件内容。 以下列举其他八种获取资源文件的方法: 1. 使用`ClassLoader.getResourceAsStream(fileName)`:直接获取InputStream流,适合处理大文件或流式处理。 2. 使用`URLClassLoader.getResource(fileName)`:基于URL加载资源,可用于跨类加载器的情况。 3. 使用`Class.getResourceAsStream(fileName)`:类级别的资源获取,适用于当前类路径下的资源。 4. 使用`Thread.currentThread().getContextClassLoader().getResource(fileName)`:获取当前线程上下文类加载器的资源。 5. 使用`URL.class.getResource(fileName)`:针对特定类的资源获取,与类的路径相关。 6. 使用`FileUtils.readFileToString(new File(filePath))`:Spring框架提供的方法,读取文件内容为字符串。 7. 使用`Files.readAllLines(Paths.get(filePath))`:Java 7及以上版本的Java NIO库,读取文件所有行。 8. 使用`ZipURLConnection`或`JarURLConnection`:适用于从压缩文件或JAR文件中读取资源。 每种方法都有其适用场景和优缺点,选择哪种取决于项目需求、性能要求以及资源文件的特性。理解并熟练运用这些方法能提高开发效率,同时确保资源文件在不同环境下的兼容性。阅读这篇文章可以帮助你扩展对Java资源管理的技能,并在实际项目中更好地应用AI和人工智能技术。

public void downloadFtpFile(String url, HttpServletResponse response) throws IOException { // 解析 URL,获取 FTP 服务器 IP、端口、用户名、密码、文件路径和文件名等信息 FtpInfo ftpInfo = parseFtpUrl(url); if (ftpInfo == null) { logger.error("Invalid URL: " + url); return; } FTPClient ftpClient = null; try { // 建立 FTP 连接 ftpClient = new FTPClient(); ftpClient.connect(ftpInfo.getIp(), ftpInfo.getPort()); if (StringUtils.hasText(ftpInfo.getUserName())) { ftpClient.login(ftpInfo.getUserName(), ftpInfo.getPassword()); // 用户名密码登录 } else { ftpClient.login("anonymous", ""); // 匿名登录 } if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) { throw new IOException("Failed to connect to FTP server: " + ftpInfo.getIp() + ":" + ftpInfo.getPort()); } // 切换到指定目录 ftpClient.changeWorkingDirectory(ftpInfo.getFilePath()); // 获取要下载文件的 InputStream InputStream is = ftpClient.retrieveFileStream(new String(ftpInfo.getFilename().getBytes("GB2312"), StandardCharsets.ISO_8859_1)); if (is == null) { throw new IOException("Failed to retrieve file from FTP server: " + ftpInfo.getFilename()); } // 设置响应头,输出文件流 response.setContentType("application/pdf"); response.setHeader("Content-Disposition", "inline; filename=" + ftpInfo.getFilename()); OutputStream os = response.getOutputStream(); IOUtils.copy(is, os); os.flush(); } catch (IOException e) { logger.error("Failed to download file from FTP server: " + ftpInfo.getFilename(), e); } finally { if (ftpClient != null) { ftpClient.logout(); ftpClient.disconnect(); } } } private FtpInfo parseFtpUrl(String url) { Pattern pattern = Pattern.compile("^ftp://([^/@]+)(?::(\d+))?(/[^@]*)?/([^@/]+)$"); Matcher matcher = pattern.matcher(url); if (!matcher.matches()) { return null; } FtpInfo ftpInfo = new FtpInfo(); ftpInfo.setIp(matcher.group(1)); ftpInfo.setPort(Integer.parseInt(StringUtils.defaultIfBlank(matcher.group(2), "21"))); String[] userInfo = matcher.group().split(":"); if (userInfo.length == 2) { ftpInfo.setUserName(userInfo[0]); ftpInfo.setPassword(userInfo[1]); } ftpInfo.setFilePath(StringUtils.defaultIfBlank(matcher.group(3), "/")); ftpInfo.setFilename(matcher.group(4)); return ftpInfo; } private static class FtpInfo { private String ip; private int port = 21; private String userName; private String password; private String filePath = "/"; private String filename; // getters and setters }优化一下代码

2023-06-03 上传