2015-11-04 38 views
-1

我寫了一個簡短的腳本來創建一個文件到我的桌面,並出現文件。我只是做了所有主要的,像這樣:Concantenate用戶輸入字符串轉換成完整的文件路徑(Java)

import java.io.*; 
    import java.util.Scanner; 
public class FilePractice { 
    public static void main(String[] args) { 

    //create a new File object 
    File myFile = new File("/home/christopher/Desktop/myFile"); 

    try{ 
     System.out.println("Would you like to create a new file? Y or N: "); 
     Scanner input = new Scanner(System.in); 
     String choice = input.nextLine(); 
     if(choice.equalsIgnoreCase("Y")) 
     { 
      myFile.createNewFile(); 
     } 
     else 
     { 
      //do nothing 
     } 
    }catch(IOException e) { 
     System.out.println("Error while creating file " + e); 
    } 
    System.out.println("'myFile' " + myFile.getPath() + " created."); 
    } 
} 

我只是想確保代碼的工作,它做了什麼。之後,我想通過創建一個帶有用戶輸入的文件來擴展,並定義用戶希望將文件發送到哪個目錄。我在Linux機器上,我想再次將它發送到我的桌面,所以我的用戶輸入爲userPath的「/ home/christopher/Desktop」。什麼都沒發生。我甚至通過終端cd到我的桌面,以「ls」在那裏的一切,仍然沒有。

也許我的語法錯了?

如果這是任何東西的重複,我的道歉。我試圖在進入這裏之前做一個徹底的搜索,但我只發現創建文件和發送文件到已經定義爲字符串的目錄的信息(例如File myFile = new File(「/ home/User/Desktop/myFileName」)) )。

這裏是擴張企圖:

try { 
     System.out.println("Alright. You chose to create a new file.\nWhat would you like to name the file?"); 
      String fileName = input.nextLine(); 
      input.nextLine(); 
      System.out.println("Please enter the directory where you would like to save this file.\nFor example: C:\\Users\\YourUserName\\Documents\\"); 
      String userFilePath = input.nextLine(); 
      File userFile = new File(userFilePath, fileName); 
      System.out.println("Is this the file path you wish to save to? ----> " + userFile.getPath()+"\nY or N: "); 
      String userChoice = input.nextLine(); 

      if (userChoice.equalsIgnoreCase("Y")) { 
       userFile.createNewFile(); 
       //print for debug 
       System.out.println(userFile.getPath()); 
       } 
      }catch(IOException e) { 
       System.out.println("Error while attempting to create file " + e); 
      } 
      System.out.println("File created successfully"); 

我給調試嘗試輸出「的/ home /克里/桌面」 print語句,但不追加到目錄中的文件名。

感謝您提供的任何幫助。這只是在學習Java I/O時進行實驗。由於假想的用戶可能與我不在同一個操作系統上,因此我可以在以後處理這些方法。我將它保存在我的主機上,因此是Unix文件路徑的名稱。

回答

0

將input.nextLine()更改爲input.next()解決了該問題。在詢問用戶他們是否確定他們輸入的路徑是想要的保存點之後,程序沒有達到if語句。

我還在其中輸入了一個簡單的else語句(「File not created」)來驗證它是否跳過它。

無論如何,問題的答案。 :-)