缓冲写入器不写入文件

Buffered writer not writing to file

我有以下主要声明。缓冲写入器生成一个新的 .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] + ", ");
  }

几乎每次看到有人抱怨BufferedWriter或者PrintWriter不写,都是因为没有刷新。

重要规则:始终bw.close() Input/Output 流

bw.close();

您可以根据需要考虑的其他事项:

  1. (一般不推荐)创建BufferedReader时启用autoflush: 它在写入套接字并且您希望进行实时通信等情况下很有用。写入文件时通常没有用。 bw = new BufferedWriter(fileWriter, true /* 自动刷新 */);
  2. bw.flush(); 每当您认为适合实际写入磁盘时。