導航:首頁 > 編程語言 > java讀取路徑下文件

java讀取路徑下文件

發布時間:2022-07-08 01:58:32

java怎樣獲得某個目錄下所有文件的文件名

java中獲得一個文件夾中的所有文件名代碼如下:

packagecom.readfile;

importjava.io.File;

publicclassGetAllFiles {

publicstaticvoidmain(String[] args) {

//路徑 這里寫一個路徑進去

String path="F:\QQ文檔";

//調用方法

getFiles(path);

}

/**

* 遞歸獲取某路徑下的所有文件,文件夾,並輸出

*/

publicstaticvoidgetFiles(String path) {

File file =newFile(path);

// 如果這個路徑是文件夾

if(file.isDirectory()) {

// 獲取路徑下的所有文件

File[] files = file.listFiles();

for(inti =0; i < files.length; i++) {

// 如果還是文件夾 遞歸獲取裡面的文件 文件夾

if(files[i].isDirectory()) {

System.out.println("目錄:"+ files[i].getPath());

getFiles(files[i].getPath());

}else{

System.out.println("文件:"+ files[i].getPath());

}

}

}else{

System.out.println("文件:"+ file.getPath());

}

}

}

(1)java讀取路徑下文件擴展閱讀:

如果想要獲得當前文件中的文件名只需要String [] fileName = file.list();就可以了。

如果要包括文件中的文件名就可以用遞歸的方式。下面是兩個具體的實現。

其中public static String [] getFileName(String path)是只得到當前文件中的文件名。

public static void getAllFileName(String path,ArrayList<String> fileName)是包括當前文件及其子文件的文件名。

Ⅱ Java 如何讀取目錄下的文件內容

Java讀取目錄下的文件內容,使用的是java的文件類,示例如下:

importjava.io.BufferedReader;
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.FileReader;
importjava.io.IOException;
importjava.io.InputStream;
importjava.io.InputStreamReader;
importjava.io.RandomAccessFile;
importjava.io.Reader;

publicclassReadFromFile{
/**
*以位元組為單位讀取文件,常用於讀二進制文件,如圖片、聲音、影像等文件。
*
*@paramfileName
*文件的名
*/
(StringfileName){
Filefile=newFile(fileName);
InputStreamin=null;
try{
System.out.println("以位元組為單位讀取文件內容,一次讀一個位元組:");
//一次讀一個位元組
in=newFileInputStream(file);
inttempbyte;
while((tempbyte=in.read())!=-1){
System.out.write(tempbyte);
}
in.close();
}catch(IOExceptione){
e.printStackTrace();
return;
}
try{
System.out.println("以位元組為單位讀取文件內容,一次讀多個位元組:");
//一次讀多個位元組
byte[]tempbytes=newbyte[100];
intbyteread=0;
in=newFileInputStream(fileName);
ReadFromFile.showAvailableBytes(in);
//讀入多個位元組到位元組數組中,byteread為一次讀入的位元組數
while((byteread=in.read(tempbytes))!=-1){
System.out.write(tempbytes,0,byteread);
}
}catch(Exceptione1){
e1.printStackTrace();
}finally{
if(in!=null){
try{
in.close();
}catch(IOExceptione1){
}
}
}
}

/**
*以字元為單位讀取文件,常用於讀文本,數字等類型的文件
*
*@paramfileName
*文件名
*/
(StringfileName){
Filefile=newFile(fileName);
Readerreader=null;
try{
System.out.println("以字元為單位讀取文件內容,一次讀一個位元組:");
//一次讀一個字元
reader=newInputStreamReader(newFileInputStream(file));
inttempchar;
while((tempchar=reader.read())!=-1){
//對於windows下, 這兩個字元在一起時,表示一個換行。
//但如果這兩個字元分開顯示時,會換兩次行。
//因此,屏蔽掉 ,或者屏蔽 。否則,將會多出很多空行。
if(((char)tempchar)!=' '){
System.out.print((char)tempchar);
}
}
reader.close();
}catch(Exceptione){
e.printStackTrace();
}
try{
System.out.println("以字元為單位讀取文件內容,一次讀多個位元組:");
//一次讀多個字元
char[]tempchars=newchar[30];
intcharread=0;
reader=newInputStreamReader(newFileInputStream(fileName));
//讀入多個字元到字元數組中,charread為一次讀取字元數
while((charread=reader.read(tempchars))!=-1){
//同樣屏蔽掉 不顯示
if((charread==tempchars.length)
&&(tempchars[tempchars.length-1]!=' ')){
System.out.print(tempchars);
}else{
for(inti=0;i<charread;i++){
if(tempchars[i]==' '){
continue;
}else{
System.out.print(tempchars[i]);
}
}
}
}

}catch(Exceptione1){
e1.printStackTrace();
}finally{
if(reader!=null){
try{
reader.close();
}catch(IOExceptione1){
}
}
}
}

/**
*以行為單位讀取文件,常用於讀面向行的格式化文件
*
*@paramfileName
*文件名
*/
(StringfileName){
Filefile=newFile(fileName);
BufferedReaderreader=null;
try{
System.out.println("以行為單位讀取文件內容,一次讀一整行:");
reader=newBufferedReader(newFileReader(file));
StringtempString=null;
intline=1;
//一次讀入一行,直到讀入null為文件結束
while((tempString=reader.readLine())!=null){
//顯示行號
System.out.println("line"+line+":"+tempString);
line++;
}
reader.close();
}catch(IOExceptione){
e.printStackTrace();
}finally{
if(reader!=null){
try{
reader.close();
}catch(IOExceptione1){
}
}
}
}

/**
*隨機讀取文件內容
*
*@paramfileName
*文件名
*/
(StringfileName){
RandomAccessFilerandomFile=null;
try{
System.out.println("隨機讀取一段文件內容:");
//打開一個隨機訪問文件流,按只讀方式
randomFile=newRandomAccessFile(fileName,"r");
//文件長度,位元組數
longfileLength=randomFile.length();
//讀文件的起始位置
intbeginIndex=(fileLength>4)?4:0;
//將讀文件的開始位置移到beginIndex位置。
randomFile.seek(beginIndex);
byte[]bytes=newbyte[10];
intbyteread=0;
//一次讀10個位元組,如果文件內容不足10個位元組,則讀剩下的位元組。
//將一次讀取的位元組數賦給byteread
while((byteread=randomFile.read(bytes))!=-1){
System.out.write(bytes,0,byteread);
}
}catch(IOExceptione){
e.printStackTrace();
}finally{
if(randomFile!=null){
try{
randomFile.close();
}catch(IOExceptione1){
}
}
}
}

/**
*顯示輸入流中還剩的位元組數
*
*@paramin
*/
(InputStreamin){
try{
System.out.println("當前位元組輸入流中的位元組數為:"+in.available());
}catch(IOExceptione){
e.printStackTrace();
}
}

publicstaticvoidmain(String[]args){
StringfileName="C:/temp/newTemp.txt";
ReadFromFile.readFileByBytes(fileName);
ReadFromFile.readFileByChars(fileName);
ReadFromFile.readFileByLines(fileName);
ReadFromFile.readFileByRandomAccess(fileName);
}
}

Ⅲ java怎麼取當前目錄下的文件

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.File;

public class ReadFile {
public ReadFile() {
}
/**
* 讀取某個文件夾下的所有文件
*/
public static boolean readfile(String filepath) throws FileNotFoundException, IOException {
try {

File file = new File(filepath);
if (!file.isDirectory()) {
System.out.println("文件");
System.out.println("path=" + file.getPath());
System.out.println("absolutepath=" + file.getAbsolutePath());
System.out.println("name=" + file.getName());

} else if (file.isDirectory()) {
System.out.println("文件夾");
String[] filelist = file.list();
for (int i = 0; i < filelist.length; i++) {
File readfile = new File(filepath + "\\" + filelist[i]);
if (!readfile.isDirectory()) {
System.out.println("path=" + readfile.getPath());
System.out.println("absolutepath="
+ readfile.getAbsolutePath());
System.out.println("name=" + readfile.getName());

} else if (readfile.isDirectory()) {
readfile(filepath + "\\" + filelist[i]);
}
}

}

} catch (FileNotFoundException e) {
System.out.println("readfile() Exception:" + e.getMessage());
}
return true;
}

/**
* 刪除某個文件夾下的所有文件夾和文件
*/

/*public static boolean deletefile(String delpath)
throws FileNotFoundException, IOException {
try {

File file = new File(delpath);
if (!file.isDirectory()) {
System.out.println("1");
file.delete();
} else if (file.isDirectory()) {
System.out.println("2");
String[] filelist = file.list();
for (int i = 0; i < filelist.length; i++) {
File delfile = new File(delpath + "\\" + filelist[i]);
if (!delfile.isDirectory()) {
System.out.println("path=" + delfile.getPath());
System.out.println("absolutepath="
+ delfile.getAbsolutePath());
System.out.println("name=" + delfile.getName());
delfile.delete();
System.out.println("刪除文件成功");
} else if (delfile.isDirectory()) {
deletefile(delpath + "\\" + filelist[i]);
}
}
file.delete();

}

} catch (FileNotFoundException e) {
System.out.println("deletefile() Exception:" + e.getMessage());
}
return true;
}*/

public static void main(String[] args) {
try {
readfile("e:/videos");
// deletefile("D:/file");
} catch (FileNotFoundException ex) {
} catch (IOException ex) {
}
System.out.println("ok");
}

Ⅳ java根據路徑讀取文件

其讀取方法為:

importjava.io.File;
importjava.io.FileNotFoundException;
importjava.io.IOException;
importjava.util.ArrayList;


publicclassreadFile{
privatestaticArrayList<String>listname=newArrayList<String>();
publicstaticvoidmain(String[]args)throwsException{
readAllFile("C:/Users/HP/Desktop");
System.out.println(listname.size());
}
publicstaticvoidreadAllFile(Stringfilepath){
Filefile=newFile(filepath);
if(!file.isDirectory()){
listname.add(file.getName());
}elseif(file.isDirectory()){
System.out.println("文件");
String[]filelist=file.list();
for(inti=0;i<filelist.length;i++){
Filereadfile=newFile(filepath);
if(!readfile.isDirectory()){
listname.add(readfile.getName());
}elseif(readfile.isDirectory()){
readAllFile(filepath+"\"+filelist[i]);//遞歸
}
}
}
for(inti=0;i<listname.size();i++){
System.out.println(listname.get(i));
}
}
}

Ⅳ java怎麼通過文件的路徑讀取文件

packagefile.system.demo.exception;

importjava.io.File;
importjava.io.FileNotFoundException;
importjava.util.Scanner;

publicclassReadFile{
publicstaticStringgetFile(Stringrealpath){
Scannerscanner=null;
Stringtext="";
try{
Filefile=newFile(realpath);
scanner=newScanner(file);
}catch(FileNotFoundExceptione){
e.printStackTrace();
}
if(scanner!=null){
while(scanner.hasNextLine()){
text+=scanner.nextLine();
}
scanner.close();
}
//System.out.println(text);

returntext;
}


staticclassInnerTest{
publicstaticvoidmain(String[]args){
Stringrealpath="D:\test.txt";
Stringtext=getFile(realpath);
System.out.println(text);
}
}

}

實現方式有很多,還可以用位元組流FileInputStream,字元流FileReader等方式讀取

Ⅵ java怎麼獲取一個目錄下的所有文件名

獲取一個目錄下的所有文件和目錄方法:

importjava.io.File;

publicclassFileTest{

publicstaticvoidmain(String[]args){
/**
*將目標目錄封裝成File對象。
*/
Filedir=newFile("/Users/zym/Desktop/Mac應用程序");

/**
*獲取目錄下的所有文件和文件夾
*/
String[]names=dir.list();

for(Stringname:names){
System.out.println(name);
}
}

}

通過文件過濾器獲取某個目錄下的文件,例如所有的 .txt、.doc文件。

過濾器:

importjava.io.File;
importjava.io.FilenameFilter;

{

@Override
publicbooleanaccept(Filedir,Stringname){
returnname.endsWith(".doc");
}

}

獲取某個目錄下的按照過濾器規則的所有文件:

importjava.io.File;

publicclassFileTest{

publicstaticvoidmain(String[]args){
/**
*將目標目錄封裝成File對象。
*/
Filedir=newFile("/Users/zym/Desktop/Mac應用程序");

/**
*通過過濾器獲取目錄下的所有的.doc文件
*/
String[]names=dir.list(newFilterByDoc());

for(Stringname:names){
System.out.println(name);
}
}

}

希望能對您有所幫助!

Ⅶ java 怎麼獲取指定路徑下的文件

//根據你的要求修改了一下代碼,現在已經能將某文件夾下的所有指定類型文件復制到
//指定文件夾下了
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class ReadFiles {
public static final String FILTER = "xml";
public static final String SRC_DIR = "E:\\StudyData";// 待掃描的文件夾
public static final String DES_DIR = "E:\\testdata";// 復制後的目標文件夾

public static void main(String[] args) {
long a = System.currentTimeMillis();
scanDir(SRC_DIR, DES_DIR);
System.out.println("共花費時間:"+(System.currentTimeMillis() - a)/1000+"秒");
}

public static void scanDir(String srcPath, String desPath) {
File dir = new File(srcPath);
File[] files = dir.listFiles();

if (files == null)
return;
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
scanDir(files[i].getAbsolutePath(), desPath);
} else {
String strFileName = files[i].getAbsolutePath().toLowerCase();
File(strFileName, desPath + files[i].getName());
}
}
}

public static void File(String srcName, String destName) {
if (srcName.endsWith(FILTER)) {
System.out.println("正在復制文件 "+srcName+" 至 "+destName);
try {
BufferedInputStream in = new BufferedInputStream(
new FileInputStream(srcName));
BufferedOutputStream out = new BufferedOutputStream(
new FileOutputStream(destName));
int i = 0;
byte[] buffer = new byte[2048];
while ((i = in.read(buffer)) != -1) {
out.write(buffer, 0, i);
}
out.close();
in.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}

Ⅷ java讀取文件路徑問題

在java中獲得文件的路徑在我們做上傳文件操作時是不可避免的。

web 上運行
1:
this.getClass().getClassLoader().getResource("/").getPath();
this.getClass().getClassLoader().getResource("").getPath(); 得到的是 ClassPath的絕對URI路徑。
如:/D:/jboss-4.2.2.GA/server/default/deploy/hp.war/WEB-INF/classes/
System.getProperty("user.dir");
this.getClass().getClassLoader().getResource(".").getPath(); 得到的是 項目的絕對路徑。
如:/D:/jboss-4.2.2.GA/server/default/deploy/hp.war

2:
this.getClass().getResource("/").getPath();
this.getClass().getResource("").getPath(); 得到的是當前類 文件的URI目錄。不包括自己!
如:/D:/jboss-4.2.2.GA/server/default/deploy/hp.war/WEB-INF/classes/com/jebel/helper/
this.getClass().getResource(".").getPath(); X 不 能運行

3:
Thread.currentThread().getContextClassLoader().getResource("/").getPath()
Thread.currentThread().getContextClassLoader().getResource("").getPath() 得到的是 ClassPath的絕對URI路徑。
如:/D:/jboss-4.2.2.GA/server/default/deploy/hp.war/WEB-INF/classes/
Thread.currentThread().getContextClassLoader().getResource(".").getPath() 得到的是 項目的絕對路徑。
如:/D:/jboss-4.2.2.GA/server/default/deploy/hp.war

在本地運行中
1:
this.getClass().getClassLoader().getResource("").getPath();
this.getClass().getClassLoader().getResource(".").getPath(); 得到的是 ClassPath的絕對URI路徑。
如:/D:/myProjects/hp/WebRoot/WEB-INF/classes
this.getClass().getClassLoader().getResource(".").getPath(); X 不 能運行
2:
this.getClass().getResource("").getPath();
this.getClass().getResource(".").getPath(); 得到的是當前類 文件的URI目錄。不包括自己!
如:/D:/myProjects/hp/WebRoot/WEB-INF/classes/com/jebel/helper/
/D:/myProjects/hp/WebRoot/WEB-INF/classes/ 得到的是 ClassPath的絕對URI路徑。
如:/D:/myProjects/hp/WebRoot/WEB-INF/classes

3:
Thread.currentThread().getContextClassLoader().getResource(".").getPath()
Thread.currentThread().getContextClassLoader().getResource("").getPath() 得到的是 ClassPath的絕對URI路徑。。
如:/D:/myProjects/hp/WebRoot/WEB-INF/classes
Thread.currentThread().getContextClassLoader().getResource("/").getPath() X 不 能運行

最後
在Web應用程序中,我們一般通過ServletContext.getRealPath("/")方法得到Web應用程序的根目錄的絕對路徑。
還有request.getContextPath(); 在Weblogic中要用request.getServletContext().getContextPath();但如果打包成war部署到Weblogic伺服器,項目內部並沒有文件結構的概念,用這種方式是始終得到null,獲取不到路徑,目前還沒有找到具體的解決方案。

Ⅸ java如何通過文件路徑讀取該路徑下的所有文件並將其放入list中

java中可以通過遞歸的方式獲取指定路徑下的所有文件並將其放入List集合中。

假設指定路徑為path,目標集合為fileList,遍歷指定路徑下的所有文件,如果是目錄文件則遞歸調用,如果是普通文件則放入fileList中。
根據這個思路,得到java源代碼如下所示:
//方法getFiles根據指定路徑獲取所有的文件
public void getFiles(String path){
//目標集合fileList
ArrayList<File> fileList = new ArrayList();
File file = new File(path);
if(file.isDirectory()){
File []files = file.listFiles();
for(File fileIndex:files){
//如果這個文件是目錄,則進行遞歸搜索
if(fileIndex.isDirectory()){
getFiles(fileIndex.getPath());
}else {
//如果文件是普通文件,則將文件句柄放入集合中
fileList.add(fileIndex);
}
}
}
}

Ⅹ java如何在某一路徑下讀文件

其實你可以將這些配置文件寫進xml文件,然後再讀取時按照節點來讀取就可以了。這樣的知識點在網上有很多的。

閱讀全文

與java讀取路徑下文件相關的資料

熱點內容
自己購買雲主伺服器推薦 瀏覽:422
個人所得稅java 瀏覽:761
多餘的伺服器滑道還有什麼用 瀏覽:192
pdf劈開合並 瀏覽:28
不能修改的pdf 瀏覽:752
同城公眾源碼 瀏覽:489
一個伺服器2個埠怎麼映射 瀏覽:298
java字元串ascii碼 瀏覽:79
台灣雲伺服器怎麼租伺服器 瀏覽:475
旅遊手機網站源碼 瀏覽:332
android關聯表 瀏覽:946
安卓導航無聲音怎麼維修 瀏覽:333
app怎麼裝視頻 瀏覽:431
安卓系統下的軟體怎麼移到桌面 瀏覽:96
windows拷貝到linux 瀏覽:772
mdr軟體解壓和別人不一樣 瀏覽:904
單片機串列通信有什麼好處 瀏覽:340
游戲開發程序員書籍 瀏覽:860
pdf中圖片修改 瀏覽:288
匯編編譯後 瀏覽:491