我正在尝试生成大小为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)
谢谢!
答案 0 :(得分:3)
Writers和Reader专为写入非二进制文本而设计。我建议你使用FileOutputStream for binary。
// 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);
}