优化后的代码:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.File;
import java.io.FileNotFoundException;
public class BinaryFileReadWrite {
public static void main(String[] args) {
String inputFile = "input.bin";
String outputFile = "output.bin";
try {
File file = new File(inputFile);
if(!file.exists()) {
System.out.println("input.txt file not exists!");
file.createNewFile();
}
FileOutputStream fw = new FileOutputStream(inputFile);
byte[] b = {0x1, 0x2};
fw.write(b);
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
try (FileInputStream fis = new FileInputStream(inputFile);
FileOutputStream fos = new FileOutputStream(outputFile)) {
byte[] buffer = new byte[1024];
int bytesRead;
// 读取文件
while ((bytesRead = fis.read(buffer)) != -1) {
// 写入文件
fos.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}