我编写了代码,将文件夹中的所有 pdf 文件写入获取字节并写入 .dat 文件。实际上它的工作并将所有字节写入 .dat 文件,但是当我使用 Acrobat 打开该 .dat 文件时,它会以黑页打开。
这是我的代码..
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.Arrays;
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();
final int BLOCK_SIZE = 200 * 1024;
for (int curBlock = 0; curBlock < actualBytes.length; curBlock += BLOCK_SIZE) {
String toWrite = new String(
Arrays.copyOfRange(actualBytes, curBlock, Math.min(curBlock + BLOCK_SIZE, actualBytes.length)));
String suffix = "";
if (curBlock > 0) {
//append underscores other file information and then perform writes
suffix = String.valueOf(curBlock / BLOCK_SIZE);
}
BufferedWriter datfile1 = null;
String outdatfile1 = ("07072013\\" + suffix + timeStamp + ".dat");
datfile1 = new BufferedWriter(new FileWriter(outdatfile1));
datfile1.append(toWrite);
datfile1.close();
}
//long datfilesizeinkb = datfilesize /1024;
//System.out.println("Size = " + datfilesizeinkb);
}
}
}
datfile.close();
xmlfile.close();
}
}