在Java中分割档案

时间:2018-10-08 11:19:01

标签: java

我有一个程序来拆分.txt文件,将其分为101个文件。必须分割的文件File.txt包含以\n分隔的URL。事实是该程序将文件分成相等的部分,当文件达到最大大小时,它将剪切url并启动一个新文件。如何将其拆分为不超过1Mb的大小,并且包含经过良好拆分的网址?

import java.io.*;
import java.util.Scanner;

public class readfile {
    public static int SubfileName;
    public static int[] Murl = new int[2000000];
    public static int x = 0;
    public static long usemem = 0;
    public static long Numberofmailto = 0;
    static byte[] subfich; //Subfile data (global var)
    static long NumberUrl;
    static int[] indURL; //Indices de las URLs en "subfich"

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        System.out.println("Enter the file name like url.txt to read but it should be in E:\\url\\");
        String name = in.nextLine();
        readfile(name);

        try {
            //now create 100 subfile 
            GeneraFicheros();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    // not used 
    public static void readfile(String filename) {
        try {
            // file path
            leeSubfichero("E:\\url\\" + filename);

            creaIndices();
        } catch (Exception e) {
        }
    }

    //read danger file
    static void leeSubfichero(String nomfich) throws IOException { // read file
        File fich = new File(nomfich);
        int tam = (int) fich.length(); //Tamaño bytes // size byte
        subfich = null;
        subfich = new byte[tam];
        try (FileInputStream fis = new FileInputStream(fich)) {
            NumberUrl = fis.read(subfich);
            // find the mailto urls
        }
    }


    static void creaIndices() {
        // 1. Count the number of URLs
        int n = 0;
        int x = 0;
        boolean dangerurl = false;
        for (int i = 0; i < subfich.length; i++) {
            if (subfich[i] == 10) {
                n++;
            }
        }

        //2. Store separators position
        indURL = null;
        indURL = new int[n];
        //Murl = new int[n];
        int k = 0;
        for (int i = 0; i < subfich.length; i++) {
            if (subfich[i] == 10) {
                indURL[k++] = i;
            }
        }
    }

    // create 100 files
    public static void GeneraFicheros() throws Exception {
        String zero = "00";
        RandomAccessFile raf = new RandomAccessFile("E:\\url\\danger.txt", "r");
        long numSplits = 100; //divid in 100 subfiles
        long sourceSize = raf.length();  // danger.txt file size
        long bytesPerSplit = sourceSize / numSplits; // number of bytes each file will have
        long remainingBytes = sourceSize % numSplits;

        int maxReadBufferSize = 8 * 1024; //8KB
        for (int destIx = 1; destIx <= numSplits; destIx++) {
            // each literation create a new file like 000 
            System.out.println("Escrito Subfichero " + zero + destIx + ".txt");
            runtime();
            if (destIx > 9) {
                zero = "0";
            }

            // write the file with name like 000.txt
            BufferedOutputStream bw = new BufferedOutputStream(new FileOutputStream("E:\\url\\" + zero + destIx + ".txt"));
            if (bytesPerSplit > maxReadBufferSize) {
                // total number of bytes to read
                long numReads = bytesPerSplit / maxReadBufferSize;
                // total number of bytes remaining for other files
                long numRemainingRead = bytesPerSplit % maxReadBufferSize;
                for (int i = 0; i < numReads; i++) {
                    readWrite(raf, bw, maxReadBufferSize);
                }
                // if bytes are remaining write the file
                if (numRemainingRead > 0) {
                    readWrite(raf, bw, numRemainingRead);
                }
            } else {
                readWrite(raf, bw, bytesPerSplit);
            }
            bw.close();
        }
        // if dividion didn't work extra store here 
        if (remainingBytes > 0) {
            BufferedOutputStream bw = new BufferedOutputStream(new FileOutputStream("split." + (numSplits + 1) + ".txt"));
            readWrite(raf, bw, remainingBytes);
            bw.close();
        }
        raf.close();
    }


    // write 8kb each time in the file
    static void readWrite(RandomAccessFile raf, BufferedOutputStream bw, long numBytes) throws IOException {
        byte[] buf = new byte[(int) numBytes];
        int val = raf.read(buf);
        if (val != -1) {
            bw.write(buf);
        }
    }

    static long startTime = System.nanoTime();

    public static void runtime() {
        long endTime = System.nanoTime();
        long totalTime = endTime - startTime;
        double seconds = (double) totalTime / 1000000000.0;
        System.out.println("Toatl seconds" + seconds);
    }
}

1 个答案:

答案 0 :(得分:4)

无法完成这项工作,就像您设置代码的方式一样。您的代码基本上是基于字节的(这使得不可能读取诸如换行符之类的字符,这是一个字符,而不是字节),并且它“预先计算”了要读取的数量,这也使得它不可能。想象一下,输入文件中的URL确实很长。几乎与所需的尺寸一样长。

最后,没有可行的说法:“将这个文件精确地分成100个部分,但是这样做的方式是每个文件都小于totalsize / 100 ...并且也不将任何行切成两半。 ” –可能会有101个文件,甚至可能有250个文件。如果整个文件只是一个非常长的URL,则可能也只有1个文件。

在编写程序之前,您必须准确指定程序要执行的操作。

一些提示:

  • 使用Files.newBufferedReader,传入字符集。您需要离开InputStream,因为那是字节,而不是字符。
  • 将整行读入内存,然后再决定是否可以将该行添加到您正在编写的当前“段”中,或者是否需要创建新行,因为否则您正在编写的段将变得太大。