我有以下主要陈述。缓冲的编写器生成一个新的.txt文件但不写任何东西。知道为什么吗?这可能与扫描仪没有正确关闭有关吗?我对缓冲的作家并不熟悉,但经过一些研究后认为我正确地称它为正确。有什么建议吗?
public class Lab4Main
{
static QuickSort QuickMethod = new QuickSort();
static HeapSort HeapMethod = new HeapSort();
static MedianOfThree MedianMethod = new MedianOfThree();
public static void main(String[] args) throws IOException {
BufferedWriter bw = null;
int arraySize = 0;
int len = 0;
Scanner input = new Scanner(System.in);
System.out.print("Enter the size of the file to sort: ");
arraySize = input.nextInt();
System.out.println("Application has been set up with size: " + arraySize +"\n" );
//initializes what user just entered in
int Array[] = new int[arraySize];
len = arraySize;
try{
Scanner input2 = new Scanner(System.in);
//ask for file path from user
System.out.print("Please enter the file name with extension: " + "\n");
File file = new File(input2.nextLine());
input2 = new Scanner(file);
for (int i = 0 ; input2.hasNext();i++)
{
// System.out.println(input);
int number = input2.nextInt();
Array[i] = number;
}input2.close();
} catch(Exception ex2) {
System.out.println(
"Error reading file path");
System.exit(0);
}
//make copies of array to sort
int quickArray [] = new int[arraySize];
int heapArray [] = new int[arraySize];
int medianOfThreeArray [] = new int[arraySize];
System.arraycopy( Array, 0, quickArray, 0, Array.length );
System.arraycopy( Array, 0, heapArray, 0, Array.length );
System.arraycopy( Array, 0, medianOfThreeArray, 0, Array.length );
// The name of the file to open.
String fileName = "/_trial2.txt";
// Assume default encoding.
FileWriter fileWriter = new FileWriter(fileName);
// Always wrap FileWriter in BufferedWriter.
bw = new BufferedWriter(fileWriter);
try{
bw.write("\nUnsorted Quick: ");
System.out.println("\nUnsorted Quick: ");
for (int i = 0; i < arraySize; i++){
System.out.print(quickArray[i] + ", ");
//bufferedWriter.write(quickArray[i] + ", ");
}
答案 0 :(得分:2)
几乎每当我看到有人抱怨BufferedWriter或PrintWriter没有写作时,总是因为没有刷新。
重要规则:始终bw.close()
输入/输出流。
bw.close();
根据需要,您可以考虑其他事项:
bw.flush();
只要您认为实际写入磁盘是合适的。