阿超
        >
        
java读取本地目录的文件转换为list
     
    
    
    
    
    
        
不在沉默中爆发,就在沉默中灭亡。——鲁迅
我读取了我的全部博客内容并转换成了一个List<String>
代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
   | import java.io.*; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.stream.Collectors;
  class Scratch {     public static void main(String[] args) throws Exception {         List<File> fileNames = getFileNames("D:/file/blog/backup/blog/source/_posts/");         List<String> collect = fileNames.parallelStream().map(Scratch::readFile).collect(Collectors.toList());         collect.forEach(System.out::println);     }
      private static List<File> getFileNames(String filePath) {         File file = new File(filePath);                  if (!file.exists()) {             System.err.println("【" + filePath + " not exists】");         }         return Optional.ofNullable(file.listFiles()).map(Arrays::asList).orElseGet(Collections::emptyList);     }
 
      
 
 
 
 
 
 
 
      public static void readToBuffer(StringBuffer buffer, File file) throws IOException {         InputStream is = new FileInputStream(file);         String line;          BufferedReader reader = new BufferedReader(new InputStreamReader(is));         line = reader.readLine();          while (line != null) {              buffer.append(line);              buffer.append("\n");              line = reader.readLine();          }         reader.close();         is.close();     }
      
 
 
 
 
 
 
 
      public static String readFile(File file) {         StringBuffer sb = new StringBuffer();         try {             readToBuffer(sb, file);         } catch (IOException e) {             e.printStackTrace();         }         return sb.toString();     } }
 
  | 
 
效果如下:
