2013-11-23 60 views
-2

讀取Java中的文本文件,我想輸入文件名的文件不是file.txt.How修改此代碼如何通過名稱

public static void main (String[] args) throws FileNotFoundException { 
      Scanner sc = new Scanner(System.in); 
      System.out.print("Enter the input file name: "); 
     String newfile = sc.nextLine(); 
} 
+0

你想讀什麼類型的文件? – Masudul

+0

你真的在問:「如何將.txt擴展名添加到文件名?」...你嘗試了什麼? – hyde

回答

0
public static void main (String[] args) throws FileNotFoundException { 
      Scanner sc = new Scanner(System.in); 
      System.out.print("Enter the input file name: "); 
     String newfile = sc.nextLine() + ".txt"; 
} 

字符串的newfile總會有文件類型的擴展名... 希望這會有所幫助..

0

我不確定您是否想修改文件名或讀取文件。我假設第二個。

//Get filename 
Scanner sc = new Scanner(System.in); 
System.out.println("Enter the input file name: "); 
String filename = sc.nextLine(); 
sc.close(); 

//Read file into StringBuilder 
StringBuilder sb = new StringBuilder(); 
sc = new Scanner(new FileReader(new File(filename))); 
while (sc.hasNextLine()){ 
    sb.append(sc.nextLine()).append(System.getProperty("line.separator")); 
}