OutputStream创建文件时报错java.io.FileNotFoundException解决办法

博客介绍了OutputStream从内存到硬盘写入数据的情况,指出文件不存在时输出流会自动创建文件,但遇到报错。经分析发现,OutputStream能创建文件,却不能创建多级目录下的文件,若要创建多级目录下的文件,可先创建文件夹。

OutputStream从内存到硬盘写入数据
文件不存在 输出流会自动创建这样一个文件
但是遇到如图错误:
在这里插入图片描述
发现OutputStream可以创建文件,但是不能创建多级目录下的文件,如果要创建多级目录下的文件,可以先创建文件夹,文件是可以自动创建的

        File file=new File("E:\\newFile\\hello.jpeg");
	    File dir=new File(file.getPath().replace(file.getName(),""));
	    if(!dir.exists())
	    {
	    	dir.mkdirs();
	    }
 		OutputStream out=new FileOutputStream(file);
		out.write(b);
package com.example; import java.io.*; import java.nio.ByteBuffer; import java.nio.file.*; import java.time.*; import java.util.*; import java.util.stream.*; import net.lingala.zip4j.ZipFile; import net.jpountz.lz4.LZ4Compressor; import net.jpountz.lz4.LZ4Factory; import net.jpountz.lz4.LZ4FastDecompressor; public class CompressionRunner { public static void main(String[] args) throws Exception { Path inputZip = Paths.get("/home/zhouweixiang/addSecret/zip-generator/target/output/map_data_0.zip"); Path unzipDir = Paths.get("now"); Path lz4File = Paths.get("backup.lz4"); Path lz4UnzipDir = Paths.get("unzipped_lz4"); Instant totalStart = Instant.now(); // 1. 解压 ZIP (Zip4j + ZStandard) if (shouldSkip("1. ZIP 解压", unzipDir)) { System.out.println("⚠️ 已跳过:目标目录已存在文件"); } else { Instant start = Instant.now(); System.out.println("1. 开始解压 ZIP 文件..."); unzipWithZip4j(inputZip, unzipDir); System.out.println("⏱️ ZIP 解压耗: " + Duration.between(start, Instant.now()).getSeconds() + " 秒"); } // 2. 压缩为 LZ4(带原始长度信息) if (shouldSkip("2. LZ4 压缩", lz4File)) { System.out.println("⚠️ 已跳过:目标文件已存在"); } else { Instant start = Instant.now(); System.out.println("\n2. 开始压缩文件夹为 LZ4..."); compressToLZ4(unzipDir, lz4File); System.out.println("⏱️ LZ4 压缩耗: " + Duration.between(start, Instant.now()).getSeconds() + " 秒"); } // 3. 解压 LZ4(使用原始长度解压) if (shouldSkip("3. LZ4 解压", lz4UnzipDir)) { System.out.println("⚠️ 已跳过:目标目录已存在文件"); } else { Instant start = Instant.now(); System.out.println("\n3. 开始解压 LZ4 文件..."); decompressLZ4(lz4File, lz4UnzipDir); System.out.println("⏱️ LZ4 解压耗: " + Duration.between(start, Instant.now()).getSeconds() + " 秒"); } Instant totalEnd = Instant.now(); System.out.println("\n✅ 全部任务完成!"); System.out.println("总耗: " + Duration.between(totalStart, totalEnd).getSeconds() + " 秒"); } private static boolean shouldSkip(String step, Path targetPath) throws IOException { if (Files.exists(targetPath)) { if (Files.isDirectory(targetPath)) { try (Stream<Path> list = Files.list(targetPath)) { if (list.findFirst().isPresent()) { return true; } } } else if (Files.isRegularFile(targetPath)) { return true; } } return false; } private static void unzipWithZip4j(Path zipPath, Path outputDir) throws Exception { try (ZipFile zipFile = new ZipFile(zipPath.toFile())) { zipFile.extractAll(outputDir.toString()); System.out.println("✅ ZIP 解压完成: " + outputDir); } } private static void compressToLZ4(Path sourceDir, Path lz4File) throws IOException { LZ4Factory factory = LZ4Factory.fastestInstance(); LZ4Compressor compressor = factory.highCompressor(); try (OutputStream out = new BufferedOutputStream(new FileOutputStream(lz4File.toFile()))) { List<Path> files = new ArrayList<>(); try (Stream<Path> walk = Files.walk(sourceDir)) { walk.filter(path -> !Files.isDirectory(path)).forEach(files::add); } int total = files.size(); int count = 0; for (Path path : files) { byte[] data = Files.readAllBytes(path); // 压缩 byte[] compressed = new byte[compressor.maxCompressedLength(data.length)]; int compressedLength = compressor.compress(data, 0, data.length, compressed, 0, compressed.length); // 写入原始长度(4 字节) byte[] lengthBytes = ByteBuffer.allocate(4).putInt(data.length).array(); out.write(lengthBytes); // 写入压缩后长度(4 字节) byte[] compressedLengthBytes = ByteBuffer.allocate(4).putInt(compressedLength).array(); out.write(compressedLengthBytes); // 写入压缩数据 out.write(compressed, 0, compressedLength); System.out.print("📦"); updateProgress(++count, total); } } System.out.println("\n✅ LZ4 压缩完成: " + lz4File); } private static void decompressLZ4(Path lz4File, Path outputDir) throws IOException { LZ4Factory factory = LZ4Factory.fastestInstance(); LZ4FastDecompressor decompressor = factory.fastDecompressor(); try (InputStream in = new BufferedInputStream(new FileInputStream(lz4File.toFile()))) { byte[] lengthBuffer = new byte[4]; while (in.read(lengthBuffer) == 4) { int originalLength = ByteBuffer.wrap(lengthBuffer).getInt(); if (in.read(lengthBuffer) != 4) { throw new IOException("压缩长度数据不完整"); } int compressedLength = ByteBuffer.wrap(lengthBuffer).getInt(); byte[] compressedData = new byte[compressedLength]; if (in.read(compressedData) != compressedLength) { throw new IOException("压缩数据不完整"); } byte[] restored = new byte[originalLength]; decompressor.decompress(compressedData, 0, restored, 0, originalLength); Path tempFile = outputDir.resolve("restored.bin"); try (OutputStream out = new BufferedOutputStream(new FileOutputStream(tempFile.toFile()))) { out.write(restored); } } } System.out.println("✅ LZ4 解压完成: " + outputDir.resolve("restored.bin")); } // ✅ 辅助方法:按指定长度读取 private static byte[] readFully(InputStream in, int length) throws IOException { byte[] buffer = new byte[length]; int offset = 0; while (offset < length) { int read = in.read(buffer, offset, length - offset); if (read == -1) { throw new IOException("压缩数据不完整"); } offset += read; } return buffer; } private static void updateProgress(int current, int total) { int percent = (int) ((double) current / total * 100); int barLength = 20; int filledLength = (int) ((double) percent / 100 * barLength); String filled = new String(new char[filledLength]).replace('\0', '='); String empty = new String(new char[barLength - filledLength]).replace('\0', '-'); String bar = filled + empty; System.out.printf("\r[%s] %d%%", bar, percent); } } package com.example; import java.io.*; import java.nio.ByteBuffer; import java.nio.file.*; import java.time.*; import java.util.*; import java.util.stream.*; import net.lingala.zip4j.ZipFile; import net.jpountz.lz4.LZ4Compressor; import net.jpountz.lz4.LZ4Factory; import net.jpountz.lz4.LZ4FastDecompressor; public class CompressionRunner { public static void main(String[] args) throws Exception { Path inputZip = Paths.get("/home/zhouweixiang/addSecret/zip-generator/target/output/map_data_0.zip"); Path unzipDir = Paths.get("now"); Path lz4File = Paths.get("backup.lz4"); Path lz4UnzipDir = Paths.get("unzipped_lz4"); Instant totalStart = Instant.now(); // 1. 解压 ZIP (Zip4j + ZStandard) if (shouldSkip("1. ZIP 解压", unzipDir)) { System.out.println("⚠️ 已跳过:目标目录已存在文件"); } else { Instant start = Instant.now(); System.out.println("1. 开始解压 ZIP 文件..."); unzipWithZip4j(inputZip, unzipDir); System.out.println("⏱️ ZIP 解压耗: " + Duration.between(start, Instant.now()).getSeconds() + " 秒"); } // 2. 压缩为 LZ4(带原始长度信息) if (shouldSkip("2. LZ4 压缩", lz4File)) { System.out.println("⚠️ 已跳过:目标文件已存在"); } else { Instant start = Instant.now(); System.out.println("\n2. 开始压缩文件夹为 LZ4..."); compressToLZ4(unzipDir, lz4File); System.out.println("⏱️ LZ4 压缩耗: " + Duration.between(start, Instant.now()).getSeconds() + " 秒"); } // 3. 解压 LZ4(使用原始长度解压) if (shouldSkip("3. LZ4 解压", lz4UnzipDir)) { System.out.println("⚠️ 已跳过:目标目录已存在文件"); } else { Instant start = Instant.now(); System.out.println("\n3. 开始解压 LZ4 文件..."); decompressLZ4(lz4File, lz4UnzipDir); System.out.println("⏱️ LZ4 解压耗: " + Duration.between(start, Instant.now()).getSeconds() + " 秒"); } Instant totalEnd = Instant.now(); System.out.println("\n✅ 全部任务完成!"); System.out.println("总耗: " + Duration.between(totalStart, totalEnd).getSeconds() + " 秒"); } private static boolean shouldSkip(String step, Path targetPath) throws IOException { if (Files.exists(targetPath)) { if (Files.isDirectory(targetPath)) { try (Stream<Path> list = Files.list(targetPath)) { if (list.findFirst().isPresent()) { return true; } } } else if (Files.isRegularFile(targetPath)) { return true; } } return false; } private static void unzipWithZip4j(Path zipPath, Path outputDir) throws Exception { try (ZipFile zipFile = new ZipFile(zipPath.toFile())) { zipFile.extractAll(outputDir.toString()); System.out.println("✅ ZIP 解压完成: " + outputDir); } } private static void compressToLZ4(Path sourceDir, Path lz4File) throws IOException { LZ4Factory factory = LZ4Factory.fastestInstance(); LZ4Compressor compressor = factory.highCompressor(); try (OutputStream out = new BufferedOutputStream(new FileOutputStream(lz4File.toFile()))) { List<Path> files = new ArrayList<>(); try (Stream<Path> walk = Files.walk(sourceDir)) { walk.filter(path -> !Files.isDirectory(path)).forEach(files::add); } int total = files.size(); int count = 0; for (Path path : files) { byte[] data = Files.readAllBytes(path); // 压缩 byte[] compressed = new byte[compressor.maxCompressedLength(data.length)]; int compressedLength = compressor.compress(data, 0, data.length, compressed, 0, compressed.length); // 写入原始长度(4 字节) byte[] lengthBytes = ByteBuffer.allocate(4).putInt(data.length).array(); out.write(lengthBytes); // 写入压缩后长度(4 字节) byte[] compressedLengthBytes = ByteBuffer.allocate(4).putInt(compressedLength).array(); out.write(compressedLengthBytes); // 写入压缩数据 out.write(compressed, 0, compressedLength); System.out.print("📦"); updateProgress(++count, total); } } System.out.println("\n✅ LZ4 压缩完成: " + lz4File); } private static void decompressLZ4(Path lz4File, Path outputDir) throws IOException { LZ4Factory factory = LZ4Factory.fastestInstance(); LZ4FastDecompressor decompressor = factory.fastDecompressor(); try (InputStream in = new BufferedInputStream(new FileInputStream(lz4File.toFile()))) { byte[] lengthBuffer = new byte[4]; while (in.read(lengthBuffer) == 4) { int originalLength = ByteBuffer.wrap(lengthBuffer).getInt(); if (in.read(lengthBuffer) != 4) { throw new IOException("压缩长度数据不完整"); } int compressedLength = ByteBuffer.wrap(lengthBuffer).getInt(); byte[] compressedData = new byte[compressedLength]; if (in.read(compressedData) != compressedLength) { throw new IOException("压缩数据不完整"); } byte[] restored = new byte[originalLength]; decompressor.decompress(compressedData, 0, restored, 0, originalLength); Path tempFile = outputDir.resolve("restored.bin"); try (OutputStream out = new BufferedOutputStream(new FileOutputStream(tempFile.toFile()))) { out.write(restored); } } } System.out.println("✅ LZ4 解压完成: " + outputDir.resolve("restored.bin")); } // ✅ 辅助方法:按指定长度读取 private static byte[] readFully(InputStream in, int length) throws IOException { byte[] buffer = new byte[length]; int offset = 0; while (offset < length) { int read = in.read(buffer, offset, length - offset); if (read == -1) { throw new IOException("压缩数据不完整"); } offset += read; } return buffer; } private static void updateProgress(int current, int total) { int percent = (int) ((double) current / total * 100); int barLength = 20; int filledLength = (int) ((double) percent / 100 * barLength); String filled = new String(new char[filledLength]).replace('\0', '='); String empty = new String(new char[barLength - filledLength]).replace('\0', '-'); String bar = filled + empty; System.out.printf("\r[%s] %d%%", bar, percent); } } [ERROR] Failed to execute goal org.codehaus.mojo:exec-maven-plugin:3.5.1:java (default-cli) on project fastzip-test: An exception occurred while executing the Java class. unzipped_lz4/restored.bin (没有那个文件或目录) -> [Help 1] org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.codehaus.mojo:exec-maven-plugin:3.5.1:java (default-cli) on project fastzip-test: An exception occurred while executing the Java class. unzipped_lz4/restored.bin (没有那个文件或目录) at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:215) at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:156) at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:148) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81) at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56) at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128) at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305) at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192) at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105) at org.apache.maven.cli.MavenCli.execute (MavenCli.java:957) at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:289) at org.apache.maven.cli.MavenCli.main (MavenCli.java:193) at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method) at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62) at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke (Method.java:566) at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:282) at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:225) at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:406) at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:347) Caused by: org.apache.maven.plugin.MojoExecutionException: An exception occurred while executing the Java class. unzipped_lz4/restored.bin (没有那个文件或目录) at org.codehaus.mojo.exec.ExecJavaMojo.execute (ExecJavaMojo.java:349) at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo (DefaultBuildPluginManager.java:137) at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:210) at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:156) at org.apache.maven.lifecycle.internal.MojoExecutor.execute (MojoExecutor.java:148) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:117) at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject (LifecycleModuleBuilder.java:81) at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build (SingleThreadedBuilder.java:56) at org.apache.maven.lifecycle.internal.LifecycleStarter.execute (LifecycleStarter.java:128) at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:305) at org.apache.maven.DefaultMaven.doExecute (DefaultMaven.java:192) at org.apache.maven.DefaultMaven.execute (DefaultMaven.java:105) at org.apache.maven.cli.MavenCli.execute (MavenCli.java:957) at org.apache.maven.cli.MavenCli.doMain (MavenCli.java:289) at org.apache.maven.cli.MavenCli.main (MavenCli.java:193) at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method) at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62) at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke (Method.java:566) at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced (Launcher.java:282) at org.codehaus.plexus.classworlds.launcher.Launcher.launch (Launcher.java:225) at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode (Launcher.java:406) at org.codehaus.plexus.classworlds.launcher.Launcher.main (Launcher.java:347) Caused by: java.io.FileNotFoundException: unzipped_lz4/restored.bin (没有那个文件或目录) at java.io.FileOutputStream.open0 (Native Method) at java.io.FileOutputStream.open (FileOutputStream.java:298) at java.io.FileOutputStream.<init> (FileOutputStream.java:237) at java.io.FileOutputStream.<init> (FileOutputStream.java:187) at com.example.CompressionRunner.decompressLZ4 (CompressionRunner.java:145) at com.example.CompressionRunner.main (CompressionRunner.java:50) at org.codehaus.mojo.exec.ExecJavaMojo.doMain (ExecJavaMojo.java:371) at org.codehaus.mojo.exec.ExecJavaMojo.doExec (ExecJavaMojo.java:360) at org.codehaus.mojo.exec.ExecJavaMojo.lambda$execute$0 (ExecJavaMojo.java:280) at java.lang.Thread.run (Thread.java:829) [ERROR] [ERROR] Re-run Maven using the -X switch to enable full debug logging. [ERROR] [ERROR] For more information about the errors and possible solutions, please read the following articles: [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException
08-20
package com.server; import java.sql.*; import java.security.SecureRandom; import java.util.Base64; import org.apache.commons.codec.digest.Crypt; public class MessageDatabase_217230206 { private static MessageDatabase_217230206 dbInstance = null; private Connection dbconnection = null; private SecureRandom secureRandom = new SecureRandom(); public static synchronized MessageDatabase_217230206 getInstance() { if (dbInstance == null) { dbInstance = new MessageDatabase_217230206(); } return dbInstance; } public void open(String databaseName) throws SQLException { if (dbconnection != null && !dbconnection.isClosed()) { return; } String connectionString = "jdbc:sqlite:" + databaseName; dbconnection = DriverManager.getConnection(connectionString); System.out.println("Connected to database: " + databaseName); initializeTables(); } public void close() throws SQLException { if (dbconnection != null && !dbconnection.isClosed()) { dbconnection.close(); System.out.println("Database connection closed"); } } private void initializeTables() throws SQLException { String createUsersTable = "CREATE TABLE IF NOT EXISTS users (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "username VARCHAR(50) UNIQUE NOT NULL, " + "password VARCHAR(255) NOT NULL, " + "email VARCHAR(50) NOT NULL, " + "userNickname VARCHAR(50) NOT NULL, " + "salt VARCHAR(100) NOT NULL" + ");"; String createMessagesTable = "CREATE TABLE IF NOT EXISTS messages (" + "locationID INTEGER PRIMARY KEY AUTOINCREMENT, " + "locationName VARCHAR(100) NOT NULL, " + "locationDescription TEXT NOT NULL, " + "locationCity VARCHAR(50) NOT NULL, " + "locationCountry VARCHAR(50), " + "locationStreetAddress VARCHAR(100), " + "latitude REAL, " + "longitude REAL, " + "originalPostingTime BIGINT NOT NULL, " + "originalPoster VARCHAR(50) NOT NULL, " + "username VARCHAR(50) NOT NULL, " + "weather VARCHAR(50)" + ");"; try (Statement createStatement = dbconnection.createStatement()) { createStatement.executeUpdate(createUsersTable); createStatement.executeUpdate(createMessagesTable); System.out.println("Database tables created successfully"); } } public boolean userExists(String username) throws SQLException { final String sql = "SELECT COUNT(*) as count FROM users WHERE username = ?"; try (PreparedStatement pstmt = dbconnection.prepareStatement(sql)) { pstmt.setString(1, username); ResultSet rs = pstmt.executeQuery(); if (rs.next()) { return rs.getInt("count") > 0; } return false; } } private String hashPassword(String password) { byte[] bytes = new byte[13]; secureRandom.nextBytes(bytes); String saltBytes = Base64.getEncoder().encodeToString(bytes); String salt = "$6$" + saltBytes; return Crypt.crypt(password, salt); } public boolean addUser(String username, String password, String email, String userNickname) throws SQLException { final String sql = "INSERT INTO users (username, password, email, userNickname, salt) VALUES (?, ?, ?, ?, ?)"; try (PreparedStatement pstmt = dbconnection.prepareStatement(sql)) { String hashedPassword = hashPassword(password); pstmt.setString(1, username); pstmt.setString(2, hashedPassword); pstmt.setString(3, email); pstmt.setString(4, userNickname); pstmt.setString(5, hashedPassword.substring(0, 20)); pstmt.executeUpdate(); return true; } catch (SQLException e) { if (e.getErrorCode() == 19 || e.getMessage().contains("UNIQUE constraint failed")) { return false; } throw e; } } public boolean validateUser(String username, String password) throws SQLException { final String sql = "SELECT password FROM users WHERE username = ?"; try (PreparedStatement pstmt = dbconnection.prepareStatement(sql)) { pstmt.setString(1, username); ResultSet rs = pstmt.executeQuery(); if (rs.next()) { String storedHashedPassword = rs.getString("password"); String computedHash = Crypt.crypt(password, storedHashedPassword); return storedHashedPassword.equals(computedHash); } return false; } } public String getUserNickname(String username) throws SQLException { final String sql = "SELECT userNickname FROM users WHERE username = ?"; try (PreparedStatement pstmt = dbconnection.prepareStatement(sql)) { pstmt.setString(1, username); ResultSet rs = pstmt.executeQuery(); if (rs.next()) { return rs.getString("userNickname"); } return null; } } public boolean addMessage(String locationName, String locationDescription, String locationCity, String locationCountry, String locationStreetAddress, Double latitude, Double longitude, long originalPostingTime, String username, String weather) throws SQLException { if (!userExists(username)) { System.out.println("User " + username + " does not exist"); return false; } String userNickname = getUserNickname(username); if (userNickname == null) { userNickname = username; } final String sql = "INSERT INTO messages (locationName, locationDescription, locationCity, " + "locationCountry, locationStreetAddress, latitude, longitude, " + "originalPostingTime, originalPoster, username, weather) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"; try (PreparedStatement pstmt = dbconnection.prepareStatement(sql)) { pstmt.setString(1, locationName); pstmt.setString(2, locationDescription); pstmt.setString(3, locationCity); pstmt.setString(4, locationCountry); pstmt.setString(5, locationStreetAddress); if (latitude != null) { pstmt.setDouble(6, latitude); } else { pstmt.setNull(6, Types.DOUBLE); } if (longitude != null) { pstmt.setDouble(7, longitude); } else { pstmt.setNull(7, Types.DOUBLE); } pstmt.setLong(8, originalPostingTime); pstmt.setString(9, userNickname); pstmt.setString(10, username); if (weather != null) { pstmt.setString(11, weather); } else { pstmt.setNull(11, Types.VARCHAR); } pstmt.executeUpdate(); return true; } catch (SQLException e) { System.err.println("Error adding message: " + e.getMessage()); e.printStackTrace(); return false; } } public ResultSet getAllMessages() throws SQLException { final String sql = "SELECT locationID, locationName, locationDescription, locationCity, " + "locationCountry, locationStreetAddress, latitude, longitude, " + "originalPostingTime, originalPoster, weather " + "FROM messages " + "ORDER BY originalPostingTime DESC"; Statement statement = dbconnection.createStatement(); return statement.executeQuery(sql); } }package com.server; import com.sun.net.httpserver.HttpHandler; import com.sun.net.httpserver.HttpExchange; import java.io.*; import java.nio.charset.StandardCharsets; import java.sql.SQLException; import java.util.stream.Collectors; import org.json.JSONException; import org.json.JSONObject; public class RegistrationHandler_217230206 implements HttpHandler{ private final UserAuthenticator_217230206 userAuthenticator; private final MessageDatabase_217230206 database; public RegistrationHandler_217230206(UserAuthenticator_217230206 userAuthenticator, MessageDatabase_217230206 database) { this.userAuthenticator = userAuthenticator; this.database = database; } @Override public void handle(HttpExchange exchange) throws IOException { String requestMethod = exchange.getRequestMethod(); try { if (requestMethod.equalsIgnoreCase("POST")) { handlePostRequest(exchange); } else { handleUnsupportedRequest(exchange); } } catch (Exception e) { sendErrorResponse(exchange, 500, "Internal Server Error"); } } private void handlePostRequest(HttpExchange exchange) throws IOException { String contentType = exchange.getRequestHeaders().getFirst("Content-Type"); if (contentType == null || !contentType.equals("application/json")) { sendErrorResponse(exchange, 400, "Content-Type must be application/json"); return; } String content; try (InputStream stream = exchange.getRequestBody(); InputStreamReader isr = new InputStreamReader(stream, StandardCharsets.UTF_8); BufferedReader br = new BufferedReader(isr)) { content = br.lines().collect(Collectors.joining("\n")); } try { JSONObject json = new JSONObject(content); if (!json.has("username") || !json.has("password") || !json.has("email") || !json.has("userNickname")) { sendErrorResponse(exchange, 400, "Missing required fields: username, password, email, userNickname"); return; } String username = json.getString("username").trim(); String password = json.getString("password").trim(); String email = json.getString("email").trim(); String userNickname = json.getString("userNickname").trim(); if (username.isEmpty() || password.isEmpty() || email.isEmpty() || userNickname.isEmpty()) { sendErrorResponse(exchange, 400, "All fields must not be empty"); return; } boolean dbSuccess = database.addUser(username, password, email, userNickname); if (dbSuccess) { userAuthenticator.addUser(username, password, email, userNickname); JSONObject responseJson = new JSONObject(); responseJson.put("message", "User registered successfully"); responseJson.put("username", username); sendJsonResponse(exchange, 200, responseJson); } else { sendErrorResponse(exchange, 409, "User already registered"); } } catch (JSONException e) { sendErrorResponse(exchange, 400, "Invalid JSON format: " + e.getMessage()); } catch (SQLException e) { if (e.getMessage() != null && (e.getMessage().contains("UNIQUE constraint failed") || e.getMessage().contains("unique constraint") || e.getErrorCode() == 19)) { sendErrorResponse(exchange, 409, "User already registered"); } else { System.err.println("Database error during registration: " + e.getMessage()); sendErrorResponse(exchange, 500, "Database error: " + e.getMessage()); } } catch (Exception e) { System.err.println("Unexpected error during registration: " + e.getMessage()); sendErrorResponse(exchange, 500, "Internal server error"); } } private void handleUnsupportedRequest(HttpExchange exchange) throws IOException { sendErrorResponse(exchange, 400, "Not supported"); } private void sendErrorResponse(HttpExchange exchange, int code, String message) throws IOException { JSONObject errorJson = new JSONObject(); errorJson.put("error", message); sendJsonResponse(exchange, code, errorJson); } private void sendJsonResponse(HttpExchange exchange, int code, JSONObject json) throws IOException { String response = json.toString(); byte[] bytes = response.getBytes(StandardCharsets.UTF_8); exchange.getResponseHeaders().set("Content-Type", "application/json; charset=UTF-8"); exchange.sendResponseHeaders(code, bytes.length); try (OutputStream outputStream = exchange.getResponseBody()) { outputStream.write(bytes); } } } package com.server; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; import org.json.JSONObject; import org.json.JSONArray; import org.json.JSONException; import java.io.*; import java.nio.charset.StandardCharsets; import java.sql.Statement; import java.sql.ResultSet; import java.sql.SQLException; import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.Instant; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; import java.util.Base64; public class RequestHandler_217230206 implements HttpHandler { private final MessageDatabase_217230206 database; private final WeatherServiceClient_217230206 weatherClient; public RequestHandler_217230206(MessageDatabase_217230206 database) { this.database = database; this.weatherClient = new WeatherServiceClient_217230206("http://localhost:4001/weather"); } @Override public void handle(HttpExchange exchange) throws IOException { String requestMethod = exchange.getRequestMethod(); try { if (requestMethod.equalsIgnoreCase("GET")) { handleGetRequest(exchange); } else if (requestMethod.equalsIgnoreCase("POST")) { handlePostRequest(exchange); } else { sendErrorResponse(exchange, 405, "Method Not Allowed"); } } catch (Exception e) { sendErrorResponse(exchange, 500, "Internal Server Error"); } } private void handleGetRequest(HttpExchange exchange) throws IOException { if (!authenticateUser(exchange)) { return; } try { ResultSet rs = database.getAllMessages(); JSONArray responseArray = new JSONArray(); boolean hasMessages = false; while (rs.next()) { hasMessages = true; JSONObject messageJson = new JSONObject(); messageJson.put("locationID", rs.getInt("locationID")); messageJson.put("locationName", rs.getString("locationName")); messageJson.put("locationCountry", rs.getString("locationCountry")); messageJson.put("locationDescription", rs.getString("locationDescription")); messageJson.put("locationCity", rs.getString("locationCity")); messageJson.put("longitude", rs.getDouble("longitude")); messageJson.put("latitude", rs.getDouble("latitude")); String locationCountry = rs.getString("locationCountry"); if (locationCountry != null && !rs.wasNull()) { messageJson.put("locationCountry", locationCountry); } else { messageJson.put("locationCountry", ""); } String locationStreetAddress = rs.getString("locationStreetAddress"); if (locationStreetAddress != null && !rs.wasNull()) { messageJson.put("locationStreetAddress", locationStreetAddress); } else { messageJson.put("locationStreetAddress", ""); } double latitude = rs.getDouble("latitude"); if (!rs.wasNull()) { messageJson.put("latitude", latitude); } double longitude = rs.getDouble("longitude"); if (!rs.wasNull()) { messageJson.put("longitude", longitude); } messageJson.put("originalPoster", rs.getString("originalPoster")); long epochMillis = rs.getLong("originalPostingTime"); String isoTime = convertEpochToISO(epochMillis); messageJson.put("originalPostingTime", isoTime); String weather = rs.getString("weather"); if (!rs.wasNull() && weather != null) { messageJson.put("weather", weather); } responseArray.put(messageJson); } try { if (rs != null) { Statement stmt = rs.getStatement(); rs.close(); if (stmt != null) { stmt.close(); } } } catch (SQLException e) { System.err.println("Error closing resources: " + e.getMessage()); } if (!hasMessages) { exchange.sendResponseHeaders(204, -1); } else { sendJsonResponse(exchange, 200, responseArray); } } catch (SQLException e) { sendErrorResponse(exchange, 500, "Database error: " + e.getMessage()); } } private void handlePostRequest(HttpExchange exchange) throws IOException { if (!authenticateUser(exchange)) { return; } String contentType = exchange.getRequestHeaders().getFirst("Content-Type"); if (contentType == null || !contentType.equals("application/json")) { sendErrorResponse(exchange, 400, "Content-Type must be application/json"); return; } String requestBody = new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8); try { JSONObject json = new JSONObject(requestBody); if (!json.has("locationName") || !json.has("locationDescription") || !json.has("locationCity") || !json.has("originalPostingTime")) { sendErrorResponse(exchange, 400, "Missing required fields: locationName, locationDescription, locationCity, originalPostingTime"); return; } String locationName = json.getString("locationName").trim(); String locationDescription = json.getString("locationDescription").trim(); String locationCity = json.getString("locationCity").trim(); String originalPostingTimeStr = json.getString("originalPostingTime").trim(); String locationCountry = json.optString("locationCountry", "").trim(); String locationStreetAddress = json.optString("locationStreetAddress", "").trim(); Double latitude = null; Double longitude = null; if (json.has("latitude") && !json.isNull("latitude")) { try { latitude = json.getDouble("latitude"); } catch (Exception e) { } } if (json.has("longitude") && !json.isNull("longitude")) { try { longitude = json.getDouble("longitude"); } catch (Exception e) { } } String weather = null; boolean hasWeatherInRequest = json.has("weather") && !json.isNull("weather"); if (hasWeatherInRequest) { weather = json.optString("weather", null); } if (locationName.isEmpty() || locationDescription.isEmpty() || locationCity.isEmpty()) { sendErrorResponse(exchange, 400, "All required fields must not be empty"); return; } long epochMillis = validateAndParseTimestamp(exchange, originalPostingTimeStr); if (epochMillis == -1) { return; } String authHeader = exchange.getRequestHeaders().getFirst("Authorization"); String username = extractUsernameFromAuth(authHeader); if (latitude != null && longitude != null) { String weatherInfo = weatherClient.getWeather(latitude, longitude); if (weatherInfo != null) { weather = weatherInfo; System.out.println("Retrieved weather: " + weatherInfo); } else { System.out.println("Failed to retrieve weather information"); } } boolean success = database.addMessage(locationName, locationDescription, locationCity, locationCountry, locationStreetAddress, latitude, longitude, epochMillis, username, weather); if (success) { JSONObject responseJson = new JSONObject(); responseJson.put("message", "Message stored successfully"); responseJson.put("locationName", locationName); responseJson.put("originalPostingTime", originalPostingTimeStr); if (latitude != null) { responseJson.put("latitude", latitude); } if (longitude != null) { responseJson.put("longitude", longitude); } if (weather != null) { responseJson.put("weather", weather); } sendJsonResponse(exchange, 200, responseJson); } else { sendErrorResponse(exchange, 500, "Failed to store message"); } } catch (JSONException e) { sendErrorResponse(exchange, 400, "Invalid JSON format: " + e.getMessage()); } catch (SQLException e) { sendErrorResponse(exchange, 500, "Database error: " + e.getMessage()); } } private boolean authenticateUser(HttpExchange exchange) throws IOException { String authHeader = exchange.getRequestHeaders().getFirst("Authorization"); if (authHeader == null || !authHeader.startsWith("Basic ")) { sendErrorResponse(exchange, 401, "Authentication required"); return false; } try { String encodedCredentials = authHeader.substring("Basic ".length()).trim(); byte[] decodedBytes = Base64.getDecoder().decode(encodedCredentials); String credentials = new String(decodedBytes, StandardCharsets.UTF_8); String[] parts = credentials.split(":", 2); if (parts.length != 2) { sendErrorResponse(exchange, 401, "Invalid authentication credentials"); return false; } String userName = parts[0]; String password = parts[1]; if (database.validateUser(userName, password)) { return true; } else { sendErrorResponse(exchange, 401, "Invalid username or password"); return false; } } catch (Exception e) { sendErrorResponse(exchange, 401, "Invalid authentication credentials"); return false; } } private String extractUsernameFromAuth(String authHeader) { try { String encodedCredentials = authHeader.substring("Basic ".length()).trim(); byte[] decodedBytes = Base64.getDecoder().decode(encodedCredentials); String credentials = new String(decodedBytes, StandardCharsets.UTF_8); String[] parts = credentials.split(":", 2); if (parts.length == 2) { return parts[0]; } } catch (Exception e) { } return null; } private long validateAndParseTimestamp(HttpExchange exchange, String timestampStr) throws IOException { if (timestampStr == null || timestampStr.trim().isEmpty()) { sendErrorResponse(exchange, 400, "Timestamp cannot be empty"); return -1; } try { Instant instant = Instant.parse(timestampStr); long epochMillis = instant.toEpochMilli(); if (!isValidTimestamp(epochMillis)) { sendErrorResponse(exchange, 400, "Invalid timestamp value"); return -1; } return epochMillis; } catch (DateTimeParseException e) { sendErrorResponse(exchange, 400, "Invalid timestamp format. Use ISO 8601 UTC format like: 2024-01-15T10:30:00.000Z"); return -1; } } private boolean isValidTimestamp(long epochMillis) { long currentTime = System.currentTimeMillis(); long reasonablePast = currentTime - (100L * 365 * 24 * 60 * 60 * 1000); long reasonableFuture = currentTime + (10L * 365 * 24 * 60 * 60 * 1000); return epochMillis >= reasonablePast && epochMillis <= reasonableFuture; } private String convertEpochToISO(long epochMillis) { return ZonedDateTime.ofInstant( java.time.Instant.ofEpochMilli(epochMillis), ZoneId.of("UTC") ).format(DateTimeFormatter.ISO_INSTANT); } private void sendJsonResponse(HttpExchange exchange, int statusCode, Object json) throws IOException { String response = json.toString(); byte[] responseBytes = response.getBytes(StandardCharsets.UTF_8); exchange.getResponseHeaders().set("Content-Type", "application/json; charset=UTF-8"); exchange.sendResponseHeaders(statusCode, responseBytes.length); try (OutputStream os = exchange.getResponseBody()) { os.write(responseBytes); } } private void sendErrorResponse(HttpExchange exchange, int code, String message) throws IOException { JSONObject errorJson = new JSONObject(); errorJson.put("error", message); sendJsonResponse(exchange, code, errorJson); } }package com.server; import com.sun.net.httpserver.HttpsServer; import com.sun.net.httpserver.HttpsConfigurator; import com.sun.net.httpserver.HttpsParameters; import com.sun.net.httpserver.HttpContext; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLParameters; import java.io.*; import java.net.InetSocketAddress; import java.security.KeyStore; import java.sql.SQLException; import javax.net.ssl.KeyManagerFactory; import java.util.concurrent.Executors; public class Server { private static SSLContext myServerSSLContext(String keystorePath, String keystorePassword) throws Exception { KeyStore ks = KeyStore.getInstance("JKS"); File keystoreFile = new File(keystorePath); if (!keystoreFile.exists()) { throw new FileNotFoundException("Keystore file not found: " + keystorePath); } try (FileInputStream fis = new FileInputStream(keystoreFile)) { ks.load(fis, keystorePassword.toCharArray()); } KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(ks, keystorePassword.toCharArray()); SSLContext ssl = SSLContext.getInstance("TLS"); ssl.init(kmf.getKeyManagers(), null, null); return ssl; } public static void main(String[] args) throws IOException { try { System.out.println("Starting server initialization..."); Class.forName("org.sqlite.JDBC"); String keystorePath; String keystorePassword; if (args.length < 2) { System.out.println("No arguments provided, using default keystore.jks and password 'password'"); keystorePath = "keystore.jks"; keystorePassword = "password"; } else { keystorePath = args[0]; keystorePassword = args[1]; } File keystoreFile = new File(keystorePath); if (!keystoreFile.exists()) { System.out.println("Keystore file not found: " + keystorePath); System.out.println("Please generate keystore.jks file first"); return; } MessageDatabase_217230206 database = MessageDatabase_217230206.getInstance(); database.open("MessageDB.db"); System.out.println("Database opened successfully"); try { if (database.userExists("test")) { System.out.println("Database connection test passed"); } } catch (SQLException e) { System.err.println("Database connection test failed: " + e.getMessage()); } HttpsServer server = HttpsServer.create(new InetSocketAddress(8001), 0); SSLContext sslContext = myServerSSLContext(keystorePath, keystorePassword); server.setHttpsConfigurator(new HttpsConfigurator(sslContext) { @Override public void configure(HttpsParameters params) { SSLParameters sslparams = getSSLContext().getDefaultSSLParameters(); params.setSSLParameters(sslparams); } }); server.setExecutor(Executors.newCachedThreadPool()); System.out.println("Multi-threaded executor enabled"); UserAuthenticator_217230206 authenticator = new UserAuthenticator_217230206(database); HttpContext infoContext = server.createContext("/info", new RequestHandler_217230206(database)); infoContext.setAuthenticator(authenticator); server.createContext("/registration", new RegistrationHandler_217230206(authenticator, database)); server.start(); System.out.println("HTTPS Server started on port 8001"); System.out.println("Database: MessageDB.db"); System.out.println("Available endpoints:"); System.out.println("- /info (requires authentication)"); System.out.println("- /registration (user registration)"); System.out.println("Server is ready for testing"); Runtime.getRuntime().addShutdownHook(new Thread(() -> { System.out.println("Shutting down server..."); try { database.close(); } catch (SQLException e) { System.err.println("Error closing database: " + e.getMessage()); } server.stop(0); System.out.println("Server stopped gracefully"); })); } catch (FileNotFoundException e) { System.out.println("Certificate file not found!"); e.printStackTrace(); } catch (Exception e) { System.out.println("Error starting server: " + e.getMessage()); e.printStackTrace(); } } }package com.server; public class User_217230206 { private String username; private String password; private String email; private String userNickname; public User_217230206(String username, String password, String email, String userNickname) { this.username = username; this.password = password; this.email = email; this.userNickname = userNickname; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getUserNickname() { return userNickname; } public void setUserNickname(String userNickname) { this.userNickname = userNickname; } }package com.server; import com.sun.net.httpserver.BasicAuthenticator; import java.sql.SQLException; import java.util.Hashtable; import java.util.Map; public class UserAuthenticator_217230206 extends BasicAuthenticator { private Map<String, User_217230206> users = null; private MessageDatabase_217230206 database; public UserAuthenticator_217230206(MessageDatabase_217230206 database) { super("info"); this.database = database; users = new Hashtable<>(); } @Override public boolean checkCredentials(String username, String password) { try { return database.validateUser(username, password); } catch (SQLException e) { return false; } } public boolean addUser(String userName, String password, String email, String userNickname) { try { boolean dbSuccess = database.addUser(userName, password, email, userNickname); if (dbSuccess) { users.put(userName, new User_217230206(userName, password, email, userNickname)); return true; } return false; } catch (SQLException e) { return false; } } }package com.server; import java.time.ZoneId; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; public class UserMessage_217230206 { private String locationName; private String locationDescription; private String locationCity; private long originalPostingTime; public UserMessage_217230206(String locationName, String locationDescription, String locationCity) { this.locationName = locationName; this.locationDescription = locationDescription; this.locationCity = locationCity; this.originalPostingTime = ZonedDateTime.now(ZoneId.of("UTC")).toInstant().toEpochMilli(); } public UserMessage_217230206(String locationName, String locationDescription, String locationCity, long originalPostingTime) { this.locationName = locationName; this.locationDescription = locationDescription; this.locationCity = locationCity; this.originalPostingTime = originalPostingTime; } public String getLocationName() { return locationName; } public void setLocationName(String locationName) { this.locationName = locationName; } public String getLocationDescription() { return locationDescription; } public void setLocationDescription(String locationDescription) { this.locationDescription = locationDescription; } public String getLocationCity() { return locationCity; } public void setLocationCity(String locationCity) { this.locationCity = locationCity; } public long getOriginalPostingTime() { return originalPostingTime; } public void setOriginalPostingTime(long originalPostingTime) { this.originalPostingTime = originalPostingTime; } public String getOriginalPostingTimeISO() { return ZonedDateTime.ofInstant( java.time.Instant.ofEpochMilli(originalPostingTime), ZoneId.of("UTC") ).format(DateTimeFormatter.ISO_INSTANT); } } package com.server; import java.net.URI; import java.net.http.HttpClient; import java.net.http.HttpRequest; import java.net.http.HttpResponse; import java.time.Duration; public class WeatherServiceClient_217230206 { private final String weatherServiceUrl; private final HttpClient httpClient; public WeatherServiceClient_217230206(String weatherServiceUrl) { this.weatherServiceUrl = weatherServiceUrl; this.httpClient = HttpClient.newBuilder() .connectTimeout(Duration.ofSeconds(5)) .build(); } public String getWeather(double latitude, double longitude) { try { String xmlBody = String.format( "<coordinates><latitude>%f</latitude><longitude>%f</longitude></coordinates>", latitude, longitude ); HttpRequest request = HttpRequest.newBuilder() .uri(URI.create(weatherServiceUrl)) .header("Content-Type", "application/xml") .POST(HttpRequest.BodyPublishers.ofString(xmlBody)) .build(); HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString()); if (response.statusCode() == 200) { return extractTemperatureFromXml(response.body()); } else { System.err.println("Weather service returned error: " + response.statusCode()); return null; } } catch (Exception e) { System.err.println("Error calling weather service: " + e.getMessage()); return null; } } private String extractTemperatureFromXml(String xmlResponse) { try { int tempStart = xmlResponse.indexOf("<temperature>") + "<temperature>".length(); int tempEnd = xmlResponse.indexOf("</temperature>"); if (tempStart > 0 && tempEnd > tempStart) { String temperature = xmlResponse.substring(tempStart, tempEnd); int unitStart = xmlResponse.indexOf("<Unit>") + "<Unit>".length(); int unitEnd = xmlResponse.indexOf("</Unit>"); String unit = unitStart > 0 && unitEnd > unitStart ? xmlResponse.substring(unitStart, unitEnd) : "C"; return temperature + unit; } } catch (Exception e) { System.err.println("Error parsing weather XML: " + e.getMessage()); } return null; } }这是已经写的代码,但是没有办法通过测试,有下面两个错误org.opentest4j.AssertionFailedError: Test failed, Object {"locationStreetAddress":"Street of D","locationName":"Place A","locationCountry":"In a C country","locationDescription":"Some random place A","latitude":1.3670745662396455,"originalPoster":"Tallaaja_123","originalPostingTime":"2025-11-18T06:52:31.570Z","locationCity":"City of B","longitude":148.53484155175929} could not be found in response ==] expected: [true] but was: [false] at com.tests.Week5.testCoordinateDescription(Week5.java:284) at java.base/java.util.ArrayList.forEach(ArrayList.java:1596) at java.base/java.util.ArrayList.forEach(ArrayList.java:1596)org.opentest4j.AssertionFailedError: Test failed, user registration returned code 409 ==] expected: [true] but was: [false] at com.tests.Week5.testRegisterUser(Week5.java:79) at java.base/java.util.ArrayList.forEach(ArrayList.java:1596) at java.base/java.util.ArrayList.forEach(ArrayList.java:1596)
最新发布
11-19
### Java中解决 `java.io.FileNotFoundException` 的方法 `java.io.FileNotFoundException` 是 Java 中常见的异常,通常在尝试访问不存在的文件抛出。以下是几种解决此问题的方法: #### 1. 确保文件路径正确 检查文件路径是否正确,并确保文件确实存在于指定位置。如果文件路径是相对路径,则需要明确项目的根目录[^3]。 ```java File file = new File("OutputStream/a.txt"); // 使用正确的路径分隔符 if (!file.exists()) { System.out.println("文件不存在!"); } ``` #### 2. 创建缺失的文件或目录 如果文件不存在,可以在程序中创建它。例如: ```java File file = new File("OutputStream/a.txt"); if (!file.exists()) { try { file.getParentFile().mkdirs(); // 创建父目录 file.createNewFile(); // 创建文件 } catch (IOException e) { e.printStackTrace(); } } ``` #### 3. 捕获并处理异常 通过捕获 `FileNotFoundException` 异常,可以提供友好的错误提示或执行替代逻辑[^3]。 ```java try { FileOutputStream fos = new FileOutputStream("OutputStream/a.txt"); fos.write(97); fos.close(); } catch (FileNotFoundException e) { System.err.println("文件未找到,请检查路径是否正确。"); } catch (IOException e) { e.printStackTrace(); } ``` #### 4. 验证文件权限 确保程序有足够的权限访问目标文件或目录。如果文件位于受保护的目录中,可能需要调整权限设置[^2]。 #### 5. 检查临目录是否存在 如果程序依赖于临目录(如 Tomcat 的工作目录),需要确保该目录存在且可写入[^2]。 ```java String tempDir = System.getProperty("java.io.tmpdir"); File temp = new File(tempDir, "example.tmp"); if (!temp.exists()) { try { temp.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } ``` ### 注意事项 - 在生产环境中,建议对所有文件操作进行异常处理。 - 如果文件路径是从用户输入中获取的,应验证其合法性以避免安全风险。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值