使用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)

谢谢!

Writers和Reader是为编写非二进制文本而设计的。我建议您将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);
}

最新更新