2017-03-26 50 views
-2

進出口工作在學校的一個項目,並堅持在讀txt文件的IM,我嘗試使用此代碼如何從txt文件讀取整個文本?

public static String txt (String a) 
    { 
     String[] Text= new String[Readfile.counter(a)]; // Creates a string array for every word 
     String s=""; 
     int i=0; 
     try{ 
     Scanner scan =new Scanner(new File(a)); 

     while(scan.hasNext()){ 

      s =scan.next(); // läser en rad från fil till s 
      Text[i]=s; 
      i++; 
      // System.out.print(s + " "); // skriver ut den 

     } 

     } 
     catch(Exception exp) {} 
     String txt= Arrays.toString(Text); 
     return txt; 
     } 

想保存字符串數組作爲它循環,然後把它變成一個字符串,但這裏的問題是結果中會有括號「[]」和逗號「,」。有什麼方法可以讀取整個txt文件並將其保存在一個變量中?

回答

0

不要將字符串的文本保存在數組中。請使用此代碼。

public static String txt (String a) 
    { 

     String s=""; 
String text="";  
int i=0; 
     try{ 
     Scanner scan =new Scanner(new File(a)); 

     while(scan.hasNext()){ 

      s =scan.next(); // läser en rad från fil till s 
      text=text+s; 
      i++; 
      // System.out.print(s + " "); // skriver ut den 

     } 

     } 
     catch(Exception exp) {} 

     return text; 
     }