Java PrintWriter-如何根据用户需要的行数拆分成多个文档?
请帮助我将此文件拆分为多个文件。我试过很多东西,但都不管用。所以如果我给程序5行,文件有500行。。。这样就可以随机分成100份文件。我只能得到一个文件打印所有500行。请帮忙,谢谢。你已经很接近了 请注意,您的PrinterWriter永远不会按照您的意愿重新初始化。这就是为什么只有一个文件正在编写Java PrintWriter-如何根据用户需要的行数拆分成多个文档?,java,Java,请帮助我将此文件拆分为多个文件。我试过很多东西,但都不管用。所以如果我给程序5行,文件有500行。。。这样就可以随机分成100份文件。我只能得到一个文件打印所有500行。请帮忙,谢谢。你已经很接近了 请注意,您的PrinterWriter永远不会按照您的意愿重新初始化。这就是为什么只有一个文件正在编写 public class FileSplitter { public static void main(String[] args) throws FileNotFoundExcepti
public class FileSplitter {
public static void main(String[] args) throws FileNotFoundException {
// Enter the number of lines you would like in each document
Scanner scan = new Scanner(System.in);
System.out.println(
"Enter the number of lines you would like in each document(please note any remainders will go into a document of their own) ");
// variables
int numberOfLinesPerDocument = Integer.parseInt(scan.nextLine());
int lineCounter = 0;
int increase = 0;
String lineBreak = String.valueOf(increase);
File file = new File("test1.txt");
File inputFile = getInputFileFromUser();
try (Scanner fileScanner = new Scanner(inputFile)) {
try (PrintWriter thePrintWriter = new PrintWriter(file)) {
while (fileScanner.hasNextLine()) {
String line = fileScanner.nextLine();
lineCounter++;
thePrintWriter.println(line);
if (lineCounter == numberOfLinesPerDocument) {
lineCounter = 0;
increase++;
thePrintWriter.close();
lineBreak = String.valueOf(increase);
file = new File("testing" + lineBreak + ".txt");
}
}
}
} catch (IOException ex) {
System.out.println("System Failure: ");
}
}
@SuppressWarnings("resource")
private static File getInputFileFromUser() {
Scanner userInput = new Scanner(System.in);
System.out.print("Please enter path to input file path >>> ");
String path = userInput.nextLine();
File inputFile = new File(path);
if (inputFile.exists() == false) {
System.out.println(path + " does not exist");
System.exit(1);
} else if (inputFile.isFile() == false) {
System.out.println(path + " is not a file");
System.exit(1);
}
return inputFile;
}
}
try(Scanner fileScanner=new Scanner(inputFile)){
PrintWriter thePrintWriter=新的PrintWriter(文件)//
try (Scanner fileScanner = new Scanner(inputFile)) {
PrintWriter thePrintWriter = new PrintWriter(file); // <--change
while (fileScanner.hasNextLine()) {
String line = fileScanner.nextLine();
lineCounter++;
thePrintWriter.println(line);
if (lineCounter == numberOfLinesPerDocument) {
lineCounter = 0;
increase++;
thePrintWriter.close();
lineBreak = String.valueOf(increase);
file = new File("testing" + lineBreak + ".txt");
thePrintWriter = new PrintWriter(file); // <--change
}
}
thePrintWriter.close(); // <--change
} catch (IOException ex) {
System.out.println("System Failure: ");
}
scan.close(); // <--change