Java代码无法生成1529字节指定文件的问题求助
修复后的完整代码
import java.io.*; import java.util.Random; public class Cover { public static byte[] aPenman = {97, 98, 99, 100, 101, 102}; public static long mTabulable(String fileName) throws IOException { String path = "C:\\Users\\KOSTAS\\IdeaProjects\\prog\\src\\" + fileName; File file = new File(path); // 用try-with-resources自动管理输出流,无需手动close try (BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file))) { Random random = new Random(); // 提前实例化,循环内复用 long sum = 0; int bytesWritten = 0; int i = 0; // 用计数器精确控制写入1529字节 while (bytesWritten < 1529) { int randIndex = random.nextInt(aPenman.length); byte currentByte = aPenman[randIndex]; out.write(currentByte); bytesWritten++; if (i < 1347) { sum += currentByte; } i++; } out.flush(); // 手动刷新缓冲区,确保所有数据写入磁盘 return sum; } catch (FileNotFoundException e) { System.err.println("无法打开目标文件: " + fileName); throw e; // 可根据需求调整异常处理逻辑,比如返回默认值 } catch (IOException e) { System.err.println("写入文件时发生错误: " + fileName); throw e; } } }
额外说明
- 用
bytesWritten计数是最精准的方式,完全不受缓冲区机制影响,能确保刚好写入1529字节; - try-with-resources是Java 7+的特性,能极大简化资源管理,避免内存泄漏;
- 手动调用
flush()是为了确保缓冲区中剩余的少量数据也被写入磁盘,不过try-with-resources在关闭流时也会自动执行刷新,这里加上更稳妥。
内容的提问来源于stack exchange,提问作者kostasaret
相关产品推荐
相关产品推荐

