Java中如何讀取文件夾下的所有文件

問題:Java中如何讀取文件夾下的所有文件

Java里面是如何讀取一個文件夾下的所有文件的?

回答一

public void listFilesForFolder(final File folder) {for (final File fileEntry : folder.listFiles()) {if (fileEntry.isDirectory()) {listFilesForFolder(fileEntry);} else {System.out.println(fileEntry.getName());}}
}final File folder = new File("/home/you/Desktop");
listFilesForFolder(folder);

Java 8里面有個Files.walk API

try (Stream<Path> paths = Files.walk(Paths.get("/home/you/Desktop"))) {paths.filter(Files::isRegularFile).forEach(System.out::println);
} 

這個例子使用到了 API 指引推薦使用的try-with-resources pattern 。它確保了無論任何情況stream都會關閉。

回答二


File folder = new File("/Users/you/folder/");
File[] listOfFiles = folder.listFiles();for (File file : listOfFiles) {if (file.isFile()) {System.out.println(file.getName());}
}

回答三

在Java8里面你可以這樣干

Files.walk(Paths.get("/path/to/folder")).filter(Files::isRegularFile).forEach(System.out::println);

這會打印文件夾下的所有除了目錄以外的文件,如果你需要一個list,你可以這樣干

Files.walk(Paths.get("/path/to/folder")).filter(Files::isRegularFile).collect(Collectors.toList())

如果你想要返回 List而不是List,直接映射就完事了

List<File> filesInFolder = Files.walk(Paths.get("/path/to/folder")).filter(Files::isRegularFile).map(Path::toFile).collect(Collectors.toList());

你也同樣要保證關閉stream。否則你會遇到異常,說你打開太多文件了

回答三

Files.walk(path)會返回所有的文件通過遍歷從以給定的開始文件作為根節點的文件樹

例如這是一顆文件樹

\---folder|   file1.txt|   file2.txt|\---subfolderfile3.txtfile4.txt

使用java.nio.file.Files.walk(Path):

Files.walk(Paths.get("folder")).filter(Files::isRegularFile).forEach(System.out::println);

出現下列結果

folder\file1.txt
folder\file2.txt
folder\subfolder\file3.txt
folder\subfolder\file4.txt

使用 java.nio.file.Files.list(Path)獲取當前目錄下的所有文件:

Files.list(Paths.get("folder")).filter(Files::isRegularFile).forEach(System.out::println);

結果是:

folder\file1.txt
folder\file2.txt

文章翻譯自Stack Overflow:https://stackoverflow.com/questions/1844688/how-to-read-all-files-in-a-folder-from-java

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/391039.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/391039.shtml
英文地址,請注明出處:http://en.pswp.cn/news/391039.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

github pages_如何使用GitHub Actions和Pages發布GitHub事件數據

github pagesTeams who work on GitHub rely on event data to collaborate. The data recorded as issues, pull requests, and comments become vital to understanding the project.在GitHub上工作的團隊依靠事件數據進行協作。 記錄為問題&#xff0c;請求和注釋的數據對于…

c# .Net 緩存 使用System.Runtime.Caching 做緩存 平滑過期,絕對過期

1 public class CacheHeloer2 {3 4 /// <summary>5 /// 默認緩存6 /// </summary>7 private static CacheHeloer Default { get { return new CacheHeloer(); } }8 9 /// <summary>10 /// 緩存初始化11 /// </summary>12 …

python 實現分步累加_Python網頁爬取分步指南

python 實現分步累加As data scientists, we are always on the look for new data and information to analyze and manipulate. One of the main approaches to find data right now is scraping the web for a particular inquiry.作為數據科學家&#xff0c;我們一直在尋找…

Java 到底有沒有析構函數呢?

Java 到底有沒有析構函數呢&#xff1f; ? ? Java 到底有沒有析構函數呢&#xff1f;我沒能找到任何有關找個的文檔。如果沒有的話&#xff0c;我要怎么樣才能達到一樣的效果&#xff1f; ? ? ? 為了使得我的問題更加具體&#xff0c;我寫了一個應用程序去處理數據并且說…

關于雙黑洞和引力波,LIGO科學家回答了這7個你可能會關心的問題

引力波的成功探測&#xff0c;就像雙黑洞的碰撞一樣&#xff0c;一石激起千層浪。 關于雙黑洞和引力波&#xff0c;LIGO科學家回答了這7個你可能會關心的問題 最近&#xff0c;引力波的成功探測&#xff0c;就像雙黑洞的碰撞一樣&#xff0c;一石激起千層浪。 大家興奮之余&am…

如何使用HTML,CSS和JavaScript構建技巧計算器

A Tip Calculator is a calculator that calculates a tip based on the percentage of the total bill.小費計算器是根據總賬單的百分比計算小費的計算器。 Lets build one now.讓我們現在建立一個。 第1步-HTML&#xff1a; (Step 1 - HTML:) We create a form in order to…

用于MLOps的MLflow簡介第1部分:Anaconda環境

在這三部分的博客中跟隨了演示之后&#xff0c;您將能夠&#xff1a; (After following along with the demos in this three part blog you will be able to:) Understand how you and your Data Science teams can improve your MLOps practices using MLflow 了解您和您的數…

[WCF] - 使用 [DataMember] 標記的數據契約需要聲明 Set 方法

WCF 數據結構中返回的只讀屬性 TotalCount 也需要聲明 Set 方法。 [DataContract]public class BookShelfDataModel{ public BookShelfDataModel() { BookList new List<BookDataModel>(); } [DataMember] public List<BookDataModel>…

sql注入語句示例大全_SQL Group By語句用示例語法解釋

sql注入語句示例大全GROUP BY gives us a way to combine rows and aggregate data.GROUP BY為我們提供了一種合并行和匯總數據的方法。 The data used is from the campaign contributions data we’ve been using in some of these guides.使用的數據來自我們在其中一些指南…

ConcurrentHashMap和Collections.synchronizedMap(Map)的區別是什么?

ConcurrentHashMap和Collections.synchronizedMap(Map)的區別是什么&#xff1f; 我有一個會被多個線程同時修改的Map 在Java的API里面&#xff0c;有3種不同的實現了同步的Map實現 HashtableCollections.synchronizedMap(Map)ConcurrentHashMap 據我所知&#xff0c;HashT…

pymc3 貝葉斯線性回歸_使用PyMC3估計的貝葉斯推理能力

pymc3 貝葉斯線性回歸內部AI (Inside AI) If you’ve steered clear of Bayesian regression because of its complexity, this article shows how to apply simple MCMC Bayesian Inference to linear data with outliers in Python, using linear regression and Gaussian ra…

Hadoop Streaming詳解

一&#xff1a; Hadoop Streaming詳解 1、Streaming的作用 Hadoop Streaming框架&#xff0c;最大的好處是&#xff0c;讓任何語言編寫的map, reduce程序能夠在hadoop集群上運行&#xff1b;map/reduce程序只要遵循從標準輸入stdin讀&#xff0c;寫出到標準輸出stdout即可 其次…

mongodb分布式集群搭建手記

一、架構簡介 目標 單機搭建mongodb分布式集群(副本集 分片集群)&#xff0c;演示mongodb分布式集群的安裝部署、簡單操作。 說明 在同一個vm啟動由兩個分片組成的分布式集群&#xff0c;每個分片都是一個PSS(Primary-Secondary-Secondary)模式的數據副本集&#xff1b; Confi…

歸約歸約沖突_JavaScript映射,歸約和過濾-帶有代碼示例的JS數組函數

歸約歸約沖突Map, reduce, and filter are all array methods in JavaScript. Each one will iterate over an array and perform a transformation or computation. Each will return a new array based on the result of the function. In this article, you will learn why …

為什么Java里面的靜態方法不能是抽象的

為什么Java里面的靜態方法不能是抽象的&#xff1f; 問題是為什么Java里面不能定義一個抽象的靜態方法&#xff1f;例如&#xff1a; abstract class foo {abstract void bar( ); // <-- this is okabstract static void bar2(); //<-- this isnt why? }回答一 因為抽…

python16_day37【爬蟲2】

一、異步非阻塞 1.自定義異步非阻塞 1 import socket2 import select3 4 class Request(object):5 def __init__(self,sock,func,url):6 self.sock sock7 self.func func8 self.url url9 10 def fileno(self): 11 return self.soc…

樸素貝葉斯實現分類_關于樸素貝葉斯分類及其實現的簡短教程

樸素貝葉斯實現分類Naive Bayes classification is one of the most simple and popular algorithms in data mining or machine learning (Listed in the top 10 popular algorithms by CRC Press Reference [1]). The basic idea of the Naive Bayes classification is very …

python:改良廖雪峰的使用元類自定義ORM

概要本文僅僅是對廖雪峰老師的使用元類自定義ORM進行改進&#xff0c;并不是要創建一個ORM框架 編寫fieldclass Field(object):def __init__(self, column_type,max_length,**kwargs):1&#xff0c;刪除了參數name&#xff0c;field參數全部為定義字段類型相關參數&#xff0c;…

2019年度年中回顧總結_我的2019年回顧和我的2020年目標(包括數量和收入)

2019年度年中回顧總結In this post were going to take a look at how 2019 was for me (mostly professionally) and were also going to set some goals for 2020! &#x1f929; 在這篇文章中&#xff0c;我們將了解2019年對我來說(主要是職業)如何&#xff0c;我們還將為20…

在Java里重寫equals和hashCode要注意什么問題

問題&#xff1a;在Java里重寫equals和hashCode要注意什么問題 重寫equals和hashCode有哪些問題或者陷阱需要注意&#xff1f; 回答一 理論&#xff08;對于語言律師或比較傾向于數學的人&#xff09;&#xff1a; equals() (javadoc) 必須定義為一個相等關系&#xff08;它…