Untitled
unknown
plain_text
a year ago
2.9 kB
8
Indexable
import java.io.*;
import java.util.ArrayList;
import java.util.List;
public class SplitTextFile {
public static void main(String[] args) {
String inputFilePath = "input.txt"; // Đường dẫn tới file gốc
int numberOfFiles = 3; // Số lượng tệp muốn tạo ra
try {
// Bước 1: Đọc tất cả các câu từ tệp gốc
List<String> sentences = readSentencesFromFile(inputFilePath);
// Bước 2: Tính tổng số từ trong file
int totalWords = sentences.stream().mapToInt(sentence -> sentence.split("\\s+").length).sum();
// Bước 3: Tính số lượng từ tối ưu cho mỗi file con
int wordsPerFile = totalWords / numberOfFiles;
// Bước 4: Chia và ghi các câu vào các file con
splitSentencesToFiles(sentences, numberOfFiles, wordsPerFile);
} catch (IOException e) {
e.printStackTrace();
}
}
private static List<String> readSentencesFromFile(String filePath) throws IOException {
List<String> sentences = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
String line;
while ((line = reader.readLine()) != null) {
sentences.add(line);
}
}
return sentences;
}
private static void splitSentencesToFiles(List<String> sentences, int numberOfFiles, int wordsPerFile) throws IOException {
int currentFileIndex = 1;
int currentWordCount = 0;
List<String> currentFileSentences = new ArrayList<>();
for (String sentence : sentences) {
int sentenceWordCount = sentence.split("\\s+").length;
// Nếu thêm câu này mà số từ vượt quá giới hạn, ghi file hiện tại và bắt đầu file mới
if (currentWordCount + sentenceWordCount > wordsPerFile && currentFileIndex < numberOfFiles) {
writeFile("output_" + currentFileIndex + ".txt", currentFileSentences);
currentFileIndex++;
currentFileSentences.clear();
currentWordCount = 0;
}
currentFileSentences.add(sentence);
currentWordCount += sentenceWordCount;
}
// Ghi phần còn lại vào file cuối cùng
if (!currentFileSentences.isEmpty()) {
writeFile("output_" + currentFileIndex + ".txt", currentFileSentences);
}
}
private static void writeFile(String fileName, List<String> sentences) throws IOException {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName))) {
for (String sentence : sentences) {
writer.write(sentence);
writer.newLine();
}
}
}
}
Editor is loading...
Leave a Comment