有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

使用Java创建大小为1024字节的测试文件

我正在尝试生成大小为1024的文件。代码如下所示

import java.security.*;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.BufferedWriter;


public class GenerateFile {
  public static void main(String[] args) {
    SecureRandom random = new SecureRandom();
    byte[] array = new byte[1024];
    random.nextBytes(array);

    for(byte i = 0; i<array.length; i++) {
       System.out.println(bytes[i]);
    }
    try {
       File file = new File("testfile");
       FileWriter out = new FileWriter(file);
       out.write(bytes);
       System.out.println("Done ..........");
       out.close();

    if (file.createNewFile()){
        System.out.println("File is created!");
      }

    else {
        System.out.println("File already exists.");
      }

    }
  catch (IOException e) {
      e.printStackTrace();
  }
 }
}

这就是我得到的错误。我不明白如何在这里使用字节数组。同样,我希望文件大小为1024字节

GenerateFile.java:20: error: no suitable method found for write(byte[])
        out.write(bytes);
           ^
method Writer.write(int) is not applicable
  (argument mismatch; byte[] cannot be converted to int)
method Writer.write(char[]) is not applicable
  (argument mismatch; byte[] cannot be converted to char[])
method Writer.write(String) is not applicable
  (argument mismatch; byte[] cannot be converted to String)
method OutputStreamWriter.write(int) is not applicable
  (argument mismatch; byte[] cannot be converted to int)

谢谢


共 (1) 个答案

  1. # 1 楼答案

    编写器和读取器是为编写文本而设计的,而不是二进制文本。我建议您对二进制文件使用FileOutputStream

    // to fill with random bytes.
    try (FileOutputStream out = new FileOutputStream(file)) {
        byte[] bytes = new byte[1024];
        new SecureRandom().nextBytes(bytes);
        out.write(bytes);
    }
    

    或者,假设每个字符都转换为一个字节,则可以使用以下命令

    try (FileWriter out = new FileWriter(file)) {
        char[] chars = new char[1024];
        Arrays.fill(chars, '.');
        chars[1023] = '\n';
        out.write(chars);
    }