2015-10-06 124 views
0

我想使用掃描儀從文件讀入,然後將這些附加到數組。但是,當我這樣做時,掃描儀似乎正在拾取空白行並將這些空行分配給數組中的索引。掃描儀添加空行掃描文件中的空行

我試過公平的幾種不同的工作方式無濟於事,只是想知道是否有同樣的問題出現,新的原因是爲什麼它會這樣做?

該文件的格式如下:

F:\數據\ SFW3 \文件夾

F:\數據\ SFW3 \文件夾

F:\數據\ SFW3 \文件夾

F:\ Data \ SFW3 \ FOLDER

任何想法都會大受歡迎。

public void scanFiles() throws NoSuchElementException { 
    Scanner sc = null; 
    System.out.println("Sage 2015 is Installed on this machine"); 
    int i = 0; 

    try { 
     String line; 
     File companyFile = new File(sageFolders[8] + "\\COMPANY"); 
     sc = new Scanner(new BufferedReader(new FileReader(companyFile))); 

     while(sc.hasNextLine()) { 
      line = sc.nextLine(); 
      System.out.println(line); 
      System.out.println(i); 
      currentFolders.add(i,line); 
      System.out.println("At Index" + i + ": " + currentFolders.get(i)); 
      i++; 
     } 

     sc.close();  
    } 
    catch(FileNotFoundException e) { 
     System.out.println("File not Found: Moving onto next Version"); 
    } 
    catch(IOException e) { 
     System.out.println("IO Error"); 
    } 
} 
+2

我可以看到你爲什麼有空白行輸出是唯一的解釋輸入中有空行。是這樣嗎? –

+0

Scanner :: nextLine()文檔說,「由於此方法繼續搜索輸入查找行分隔符」似乎你有空行輸入@TimBiegeleisen提到 –

回答

6

使用String.trim().length(),以找出是否是一個空行,如果不是不加它

System.out.println(i); 

if (String.trim().length() > 0) { 
    currentFolders.add(i,line); 
    System.out.println("At Index" + i + ": " + currentFolders.get(i)); 
} 

i++; 
+0

似乎已經工作!真的非常感謝你 – Baker3915

0
To achieve your task, try below code: 

while(sc.hasNextLine()) 
     { 
     line = sc.nextLine(); 
     if(null != line && line.trim().length() > 0){ 
     System.out.println(line); 
     System.out.println(i); 
     currentFolders.add(i,line); 
     System.out.println("At Index" + i + ": " + currentFolders.get(i)); 
     i++; 
     } 
     }