java - 直到某个特定行才能写入文件

标签 java inputstream filereader outputstream

我正在尝试将文件从一个文件拆分为 4 个不同的文件。因此,我将文件除以某个“x”值,并希望写入文件直到该值,然后从那里继续到下一个文件,直到文件内容结束。

我正在使用缓冲区读取器检查文件中的某些 x 值,并检查内容是否等于 x 值并进行拆分。

分割即将到来,但会以另一种方式进行,就像它正在读取文件并写入到行号“x”为止。但我需要所有行,直到文件中出现“x”值为止。

我在文件中有一个时间,例如开始时间 hh:mm:ss,我正在使用 hh:mm:ss 和我的 x 值检查此时间,并进行如下所示的分割

// inputs to the below method
//  filePath = "//somepath";
// splitlen = 30;
// name ="somename"; */

public void split(String FilePath, long splitlen, String name) {
        long leninfile = 0, leng = 0;
        int count = 1, data;
        try {
            File filename = new File(FilePath);
            InputStream infile = new BufferedInputStream(new FileInputStream(filename));
            data = infile.read();
            BufferedReader br = new BufferedReader(new InputStreamReader(infile));

            while (data != -1) {
                filename = new File("/Users//Documents/mysrt/" + count + ".srt");
                OutputStream outfile = new BufferedOutputStream(new FileOutputStream(filename));
                String strLine = br.readLine();
                String[] atoms = strLine.split(" --> ");

                if (atoms.length == 1) {
//                   outfile.write(Integer.parseInt(strLine + "\n"));

                }
                else {

                    String startTS = atoms[0];
                    String endTS = atoms[1];
                    System.out.println(startTS + "\n");
                    System.out.println(endTS + "\n");
                    String startTime = startTS.replace(",", ".");
                    String endTime = endTS.replace(",", ".");
                    System.out.println("startTime" + "\n" + startTime);
                    System.out.println("endTime" + "\n" + endTime);
                    String [] arrOfStr = endTime.split(":");

                    System.out.println("=====arrOfStr=====");
                    int x = Integer.parseInt(arrOfStr[1]);
                    System.out.println(arrOfStr[1]);
                    System.out.println("===x repeat==");
                    System.out.println(x);
                    System.out.println("===splitlen repeat==");
                    System.out.println(splitlen);
                    System.out.println(data);
                    System.out.println(br.readLine());
                    System.out.println(br.read());

                    while (data != -1 && x < splitlen) {
                       outfile.write(br.readLine().getBytes());

                        data = infile.read();
                            x++;
                    }

                    System.out.println("===== out of while x =====");
                    System.out.println(br.readLine());
                    System.out.println(x);

                    leninfile += leng;
                    leng = 0;
                    outfile.close();
                    firstPage = false;
                    firstPage = true;
                    count++;
                    splitlen = splitlen + 30;
                    System.out.println("=====splitlen after=====" +splitlen);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

我将时间增加一些,以读取文件中的下一行并将其读取到另一个文件中。

此处 splitlen 为 30 ,因此它将数据写入新文件中直到 30 行。然后它递增 splitlen+30,即 60。但是,它正在读取接下来的 60 行并写入下一个文件。

但是我需要用文件内容中提供的时间检查这个 splitlen,并且我应该拆分该行。

请指出我哪里做错了。如果您提供片段,我们将不胜感激。

谢谢。

最佳答案

我想这就是你想要的

public void split(String filePath, long splitLen, String name) {
    File fileSource = new File(filePath);
    int count = 0;
    boolean endOfFile = false;
    String lineSeparator = System.getProperty("line.separator");
    int hour = 0; // an accumulator for hours
    int min = 0; // an accumulator for minutes
    int sec = (int) splitLen; // an accumulator for seconds
    int _hour = 0; // hours from the file
    int _min = 0; // minutes from the file
    int _sec = 0; // seconds from the file
    try (   // try with resources to close files automatically
            FileReader frSource = new FileReader(fileSource);
            BufferedReader buffSource = new BufferedReader(frSource);
            ) {
        String strIn = null;
        while(!endOfFile) {
            File fileOut = new File("f:\\test\\mysrt\\" + count + ".srt");
            try (   // try with resources to close files automatically
                    FileWriter fwOut = new FileWriter(fileOut);
                    ) {
                if (strIn != null) {
                    // write out the last line read to the new file
                    fwOut.write(strIn + lineSeparator);
                }
                for (int i = 0; i < splitLen; i++) {
                    strIn = buffSource.readLine();
                    if (strIn == null) {
                        endOfFile = true; // stop the while loop
                        break; // exit the for loop
                    }
                    if (strIn.indexOf("-->") > 0) {
                        String endTime = strIn.split("-->")[1];
                        _hour = extractHours(endTime); // get the hours from the file
                        _min = extractMinutes(endTime); // get the minutes from the file
                        _sec = extractSeconds(endTime); // get the seconds from the file
                        if (_hour >= hour && _min >= min && _sec >= sec) { // if the file time is greater than our accumulators
                            sec += splitLen; // increment our accumulator seconds
                            if (sec >= 60) { // if accumulator seconds is greater than 59, we need to convert it to minutes and seconds
                                min += sec / 60;
                                sec = sec % 60;
                            }
                            if (min >= 60) { if accumulator minutes is greater than 59, we need to convert it to hours and minutes
                                hour += min / 60;
                                min = min % 60;
                            }
                            break; // break out of the for loop, which cause the file to be completed and a new file started.
                        }
                    }
                    fwOut.write(strIn + lineSeparator); // write out to the new file
                }
                fwOut.flush();
            }
            count++;
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

private int extractMinutes(String time) {
    // You need to implement this, I don't know the format of your time
    return 0;
}

private int extractSeconds(String time) {
    // You need to implement this, I don't know the format of your time
    return 0;
}

关于java - 直到某个特定行才能写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51582408/

相关文章:

java - 使用具有临时端口的 JMX 服务器时,如何获取服务器端口号?

java - 有魔法变量是不是很糟糕?

java - 使用IDEA时xsd文件未构建到jar中

java - 我无法从网站获取所有字节

java - InputStream的read()方法是如何实现的?

java - 将文本文件中的字符串解析为日期

java - 为什么我的 if 条件不起作用(if (n>2))?

java - java如何比较两个不同大小的原始数据类型

java - 我的代码在 asyncTask 中不起作用

javascript - Google App Script,JavaScript FileReader 不是函数