2015-10-06 108 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++; 
     } 
     }