I was able to get the code you provided to work just fine. Jason C suggested calling flush()
on your PrintWriters before closing them, and I concur.
Printwriter problems?
-
10-06-2023 - |
質問
I'm trying to write a file that copies data from one user-inputted file into two other separate user-inputted files, however the something isn't going right and nothing's being copied. I know the first line is being read because I edited the code to check and display if anything from the first file was reading (it was) but again, nothing is copying. I'm learning from a book and would appreciate any help I could get. Thanks a lot!
Here's the code.
import java.util.Scanner;
import java.io.*;
import java.io.FileWriter;
public class FileIO
{
// This method writes data from a file to other files
public static void main(String[] args) throws IOException
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter input file name:");
String filename = keyboard.nextLine();
System.out.println();
System.out.println("Enter output file name:");
String filename2 = keyboard.nextLine();
System.out.println();
System.out.println("Enter another output file name (append) :");
String filename3 = keyboard.nextLine();
System.out.println();
PrintWriter outputFile = new PrintWriter(filename2);
FileWriter outputFile2 = new FileWriter(filename3, true);
PrintWriter outputfile2 = new PrintWriter(outputFile2);
File myfile = new File(filename);
Scanner inputFile = new Scanner(myfile);
while (inputFile.hasNext()){
String morelines = inputFile.nextLine();
outputFile.print(morelines);
outputfile2.print(morelines);
}
outputFile.close();
outputfile2.close();
inputFile.close();
}
}
解決
所属していません StackOverflow