0

尝试编写 java 代码来编写“.dat”文件。同时检查大小。每 200 KB 创建新的“.dat”继续写入文件。有什么办法我可以做到这一点..

当文件超过 200KB 并像这样创建一个新的文件名时

1st file name.. 1_filename 
2nd file name.. 2_filename
3rd file name.. 3_filename........

或者如果文件只创建一个文件意味着小于 200KB

Filenamd.. 文件名与代码中的一样..

我写了写文件的代码但是..它只写了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)
4

3 回答 3

2

我建议您创建一个单独的类,其唯一的工作是创建文件(按顺序),将数据写入文件,注意大小,并根据需要关闭/打开文件。这将使您的代码更有条理——您将能够更清楚地看到您的错误。该类将具有以下方法:

setMax(maxVal)                 - set the maximum file size (default 400k)
setRoot(rootPath)              - folder where files will be created
setName(rootName)              - "format string" used to generate file names 
                                 (e.g. "myFile%03d.dat")
writeData(dataSize, dataBlock) - write data. If no file open, open it. 
                                 If file too big, split it.  
closeFile()                    - flush buffers, close the last file.
                                 Could be part of the destructor
currentFile()                  - returns name of current file (for debug)
currentSize()                  - returns current file size (for debug)

如果你能弄清楚如何编写这个类,你将解决你最初的问题,并同时拥有一些你可以重复使用的东西。

如果您想(大部分)保留已有的代码结构,那么您的解决方法是删除当前的第 85 行。

     83:         String s1 = new String(actualBytes);
     84:         datfile1.append(s1);
     85:         datfile1.close();  <<<<<<<<<<< remove this line
     86:      }

关闭文件后,您的下一次写入尝试将失败 - 这就是您看到的错误。

于 2013-07-10T13:28:37.033 回答
0

你这样做datfile.close()了,并且在下一次迭代中通过 for 循环你.append()到它。您必须在 for 循环中初始化(即打开)您的datfile 内部。

于 2013-07-10T13:31:05.060 回答
0

好的,看起来像一个簿记问题。

这是它的样子

    .
    .
    . 
    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);
        }    

        //Your code more or less
        BufferedWriter datfile1 = null;
        String outdatfile1 = ("07072013\\" + suffix + timeStamp + ".dat");
        datfile1 = new BufferedWriter(new FileWriter(outdatfile1));


        datfile1.append(toWrite);
        datfile1.close(); 
    }

编辑:这更有意义吗?

这是要点。for 循环以 BLOCK_SIZE(200 KB) 的块大小进行迭代。如果文件大小小于 BLOCK_SIZE,则无需附加任何后缀(参见if 块)。否则,您附加后缀,然后写入文件。该字符串由局部变量toWrite 给出。您已经阅读了整个文件并将字节存储在actualBytes中。希望这更有意义。

于 2013-07-10T13:40:39.187 回答