2016-12-11 24 views
0

我無法使用輸入來創建我想從另一個文件中寫入行的文件。當我的代碼到達文件我想創建的名稱,它不會讓我輸入任何內容後,我輸入文件名我想要打開。我認爲這與掃描器無法接受最後一個「\ n」或某事有關,所以我試圖在第一次調用它之後用sc.nextLine()「刷新」它,但它沒有「工作。我真的不明白這個系統的邏輯不適用於nextLine(),是不是應該和第一個一樣?有人可以解釋嗎?java將一個文件的所有內容複製到另一個使用輸入讀取/創建文件名

 try { 
      System.out.println("Enter the file name to open with extension: "); 
      Scanner sc = new Scanner(System.in); 
      File file = new File(sc.nextLine()); 
      sc = new Scanner(file); //opens inputted file name 
//   System.err.println(file.getAbsolutePath()); 

      System.out.println("What is the file name you want to create? "); 
//   sc.nextLine(); 
      File write = new File(sc.nextLine()); 

      PrintWriter writer = new PrintWriter(write); 
//   System.out.println("Copying file contents over... "); 
      while (sc.hasNextLine()) { 
       String line = sc.nextLine(); 
       writer.println(line); 
      } 
      writer.close(); 
      sc.close(); 
     } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
     } 

回答

0

試試這個:

try { 
     BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 
     System.out.println("Enter the file name to open with extension: "); 

     File file = new File(br.readLine()); 
     Scanner sc = new Scanner(file); //opens inputted file name 

     System.out.println("What is the file name you want to create? "); 
     File write = new File(br.readLine()); 

     PrintWriter writer = new PrintWriter(write); 
     while (sc.hasNextLine()) { 
      String line = sc.nextLine(); 
      writer.println(line); 
     } 
     writer.close(); 
     sc.close(); 
    } catch (FileNotFoundException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
相關問題