java - 在java中分割文件

标签 java

我有一个程序可以分割 .txt 文件,将其分为 101 个文件。必须分割的文件File.txt包含由 \n 分隔的 url。事实上,程序将文件分成相等的部分,当它达到最大大小时,它会剪切 url 并开始一个新文件。我怎样才能将其分割成不超过 1Mb 的大小并包含分割良好的 url?

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

最佳答案

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

最后,没有可行的方法可以说:“将此文件精确地拆分为 100 个部分,但要确保每个文件都小于 Totalsize/100...并且不要将任何行切成两半。 ” – 可能有 101 个文件,甚至可能有 250 个文件。如果整个文件只是一个很长的 URL,则也可能只有 1 个文件。

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

一些提示:

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

关于java - 在java中分割文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52701123/

相关文章:

java - Log4j 禁用 #timestamp 注释

java - 使用 java lambda 将列中具有不同值的值分组

Java jLabel 从 netbeans "events"上下文菜单中拖放

java - 集中式二级缓存

java - 实际参数 List<<anonymous Callable<String>>> 无法通过方法调用转换转换为 List<Callable<String>>

java - 在Jframe中添加循环

java - 为什么 Java 不能在此代码中正确推断类型?

java - Class.newInstance() 是否遵循 "Abstract factory"设计模式?

java - 在 ArrayList 中查找最大数

java - 如何检索所有方面?