You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:05:24