我正在尝试编写 java 代码来编写“.dat”文件。书写时,还要检查大小。每 200 KB 创建新的“.dat”文件并继续写入文件。有什么办法可以做到吗?
当文件大于 200KB 时,创建一个像这样的新文件:
第一个文件名:1_filename
第二个文件名:2_filename
第三个文件名:3_filename
...
或者如果只创建一个文件(意味着它小于 200KB),则:
文件名:文件名
我写了代码,但它只写了 2 个文件,所以这不是正确的方法。
这是我的代码:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class xmlfile1filebytes {
public static void main(String[] args) throws IOException {
File folder = new File ("07072013");
File[] listOfFiles = folder.listFiles();
System.out.println("There are " + listOfFiles.length + " files");
String filesin;
String timeStamp = new SimpleDateFormat("MM-dd-yyyy[HH.mm.ss]")
.format(Calendar.getInstance().getTime());
System.out.println(timeStamp);
BufferedWriter xmlfile = null;
BufferedWriter datfile = null;
String outxmlfile = ("07072013\\" + timeStamp + ".xml");
xmlfile = new BufferedWriter(new FileWriter(outxmlfile));
String outdatfile = ("07072013\\" + timeStamp + ".dat");
datfile = new BufferedWriter(new FileWriter(outdatfile));
int offset = 0;
int size = 0;
for (int i = 0; i < listOfFiles.length; i++) {
File f = listOfFiles[i];
// System.out.println(i + " " + f.getAbsolutePath());
if (f.isFile()) {
filesin = listOfFiles[i].getName();
if (filesin.endsWith("pdf")) {
Path aPath = Paths.get(f.getAbsolutePath());
System.out.println(filesin);
byte[] actualBytes = Files.readAllBytes(aPath);
size = actualBytes.length;
xmlfile.append((i + 1) + ")" + " File = " + filesin + ", Offset = " + offset + ", Size = " + size + "\n");
offset = offset + size;
xmlfile.newLine();
String s = new String(actualBytes);
datfile.append(s);
datfile.newLine();
File datfileinfolder = new File ("07072013\\" + timeStamp + ".dat");
long datfilesize = datfileinfolder.length();
long datfilesizeinkb = datfilesize /1024;
System.out.println(datfilesizeinkb);
if (datfilesizeinkb >= 200) {
datfile.close();
BufferedWriter datfile1 = null;
String outdatfile1 = ("07072013\\" + "1_"+ timeStamp + ".dat");
datfile1 = new BufferedWriter(new FileWriter(outdatfile1));
String s1 = new String(actualBytes);
datfile1.append(s1);
datfile1.close();
}
}
}
}
xmlfile.close();
}
}
当文件大于 400 KB 时出现错误。
错误:
There are 10 files
07-09-2013[16.03.00]
1192970_eBill_20130709.pdf
96
1321470_eBill_20130709.pdf
208
1724897_eBill_20130709.pdf
Exception in thread "main" java.io.IOException: Stream closed
at java.io.BufferedWriter.ensureOpen(Unknown Source)
at java.io.BufferedWriter.write(Unknown Source)
at java.io.Writer.write(Unknown Source)
at java.io.Writer.append(Unknown Source)
at xmlfile1filebytes.main(xmlfile1filebytes.java:65)