導航:首頁 > 文件目錄 > java查詢當前路徑下的文件

java查詢當前路徑下的文件

發布時間:2024-07-22 08:40:08

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

importjava.io.File;
importjava.util.ArrayList;

publicclassFileTest{
privatestaticArrayList<String>filelist=newArrayList<String>();

publicstaticvoidmain(String[]args)throwsException
{
StringfilePath="E://Struts2";
getFiles(filePath);
}


/*
*通過遞歸得到某一路徑下所有的目錄及其文件
*/
staticvoidgetFiles(StringfilePath)
{
Fileroot=newFile(filePath);
File[]files=root.listFiles();
for(Filefile:files)
{
if(file.isDirectory())
{
/*
*遞歸調用
*/
getFiles(file.getAbsolutePath());
filelist.add(file.getAbsolutePath());
System.out.println("顯示"+filePath+"下所有子目錄及其文件"+file.getAbsolutePath());
}else{
System.out.println("顯示"+filePath+"下所有子目錄"+file.getAbsolutePath());
}
}
}
}

『貳』 在java中如何判斷某一個路徑下是否有指定的文件夾或者文件。

public class DirectoryList {
public static void main(String[] args){
String fileName="lady gaga、lady gaga - telephone ft. beyonce.mp3";//要判斷的文件或文件夾
try{
File path = new File("D:/KuGou");
String[] myList;//定義一個字元串數組
if(fileName == null && fileName.length() == 0)//不含自變數則顯示所有文件
myList = path.list();
else
myList = path.list(new DirectoryFilter(fileName));
for(int i = 0; i< myList.length;i++)//輸出文件列表
System.out.println(myList[i]);
}catch(Exception e)
{
e.printStackTrace();
}

}
}//DirectoryList ends 實現filename 的過濾器
class DirectoryFilter implements FilenameFilter
{
String myString;
DirectoryFilter(String myString)
{
this.myString = myString;
}
public boolean accept(File dir,String name)
{//FilenameFilter.accept(File dir, String name)
// 測試指定文件是否應該包含在某一文件列表中。
String f= new File(name).getName();
return f.equals(myString);
}
}

『叄』 java中如何在某一路徑下查找文件

這是我在jdk5.0的api里找的

listFiles
public File[] listFiles()返回一個抽象路徑名數組,這些路徑名表示此抽象路徑名所表示目錄中的文件。
如果此抽象路徑名並不表示一個目錄,則此方法將返回 null。否則,為目錄中的每個文件或目錄返回一個 File 對象數組。表示目錄本身及其父目錄的路徑名不包括在結果中。得到的每個抽象路徑名都是根據此抽象路徑名,使用 File(File, String) 構造方法構造。所以,如果此路徑名是絕對路徑名,則得到的每個路徑名都是絕對路徑名;如果此路徑名是相對路徑名,則得到的每個路徑名都是相對於同一目錄的路徑名。

不保證所得數組中的相同字元串將以特定順序出現,特別是不保證它們按字母順序出現。

返回:
表示此抽象路徑名所表示目錄中的文件和目錄的抽象路徑名數組。如果目錄為空,則數組也將為空。如果抽象路徑名不表示一個目錄,或者發生 I/O 錯誤,則返回 null。
拋出:
SecurityException - 如果存在安全管理器,且其 SecurityManager.checkRead(java.lang.String) 方法拒絕對目錄進行讀取訪問

『肆』 Java 找出某一個文件夾下的所有文件

要養成看API文檔的好習慣。
查看API可以看出,
File對象的 String[] list()方法:
Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname.
意思很明確,返回實例化File時,傳入的字元串類型的路徑名稱,此方法返回此路徑下的所有文件及目錄,不帶路徑,
File對象的 String[] listFiles()方法:
Returns an array of abstract pathnames denoting the files in the directory denoted by this abstract pathname.
意思很明確,返回實例化File時,傳入的抽象字元串類型的路徑名稱,此方法返回此路徑下的所有文件及目錄,含抽象路徑.
一般調用System.out.println(Object obj);這個方法,查看Api文檔,
System.out返回一個標準的PrintWriter,此PrintWriter是OutputStream的子類,當調用println()方法輸出對象時,調用的是對象的toString()方法,如果對象沒有覆寫toString()方法,則直接輸出對象的堆內存地址。
查看API文檔,File類的toString()
Returns the pathname string of this abstract pathname
意即返回實例化File對象時候傳入的抽象路徑
你的test方法,實例化File對象的時候,用的是list()方法得到的,此時本身該抽象路徑就只含有文件名而沒有路徑了,另外一個方法則是用的是listFiles()方法,此時得到的都含有抽象路徑。因此你輸出的時候,就出現這種情況.

『伍』 Java實現讀取某個路徑下的文件目錄

importjavax.swing.*;

importjavax.swing.table.AbstractTableModel;

importjavax.swing.table.TableCellRenderer;

importjavax.swing.event.TreeModelListener;

importjavax.swing.event.TreeSelectionListener;

importjavax.swing.event.TreeSelectionEvent;

importjavax.swing.tree.TreeModel;

importjavax.swing.tree.TreePath;

importjavax.swing.tree.TreeCellRenderer;

importjava.awt.*;

importjava.awt.event.*;

importjava.io.File;

importjava.io.FileInputStream;

importjava.io.IOException;

importjava.io.FileFilter;

importjava.util.Calendar;

importjava.util.ArrayList;

importjava.text.SimpleDateFormat;

importjava.text.MessageFormat;

/**

*@authorHardneedl

*/

{

=newDimension(300,200);

=newDimension(1024,768);

=newDimension(600,400);

privateJLabelstatusLabel;

privateJTreetree;

privateJTabledetailTable;

;

publicDimensiongetMaximumSize(){returnmaxSize;}

publicDimensiongetMinimumSize(){returnminSize;}

(){returnpreferredSize;}

publicStringgetTitle(){return"JavaExplorer";}

JavaExplorer()throwsHeadlessException{

init();

doLay();

attachListeners();

}

privatevoidinit(){

statusLabel=newJLabel(){publicColorgetForeground(){returnColor.BLUE;}};

tree=newJTree(newFileTreeModel());

tree.setCellRenderer(newDirCellRenderer());

detailTable=newJTable(tableModel=newFileTableModel());

detailTable.getColumnModel().getColumn(2).setCellRenderer(newTableCellRenderer(){

privateJLabellabel=newJLabel();

=newSimpleDateFormat("yyyy年mm月dd日HH時MM分ss秒");

(JTabletable,Objectvalue,booleanisSelected,booleanhasFocus,introw,intcolumn){

if(valueinstanceofCalendar){

Calendarcal=(Calendar)value;

label.setText(format.format(cal.getTime()));

}

returnlabel;

}

});

detailTable.getColumnModel().getColumn(0).setCellRenderer(newTableCellRenderer(){

privateJLabellabel=newJLabel();

(JTabletable,Objectvalue,booleanisSelected,booleanhasFocus,introw,intcolumn){

if(valueinstanceofFile){

Filef=(File)value;

label.setText(f.getName());

label.setForeground(f.isDirectory()?Color.RED:Color.BLACK);

}

returnlabel;

}

});

}

privatevoiddoLay(){

Containercontainer=getContentPane();

JSplitPanesplitPane=newJSplitPane(JSplitPane.HORIZONTAL_SPLIT,newJScrollPane(tree),newJScrollPane(detailTable));

container.add(splitPane,BorderLayout.CENTER);

container.add(statusLabel,BorderLayout.SOUTH);

pack();

}

privatevoidattachListeners(){

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

tree.addTreeSelectionListener(newSelectionListener());

tree.addTreeSelectionListener(new_DirSelectionListener());

DirCellSelectedListenerck=newDirCellSelectedListener(tree);

detailTable.addKeyListener(ck);

detailTable.addMouseListener(ck);

}

publicstaticvoidmain(String[]args){

newJavaExplorer().setVisible(true);

}

{

staticfinalStringroot="我的電腦";

privateFile[]rootFiles;

=newFileFilter(){

publicbooleanaccept(Filef){returnf.isDirectory();}

};

privateFileTreeModel(){rootFiles=File.listRoots();}

publicObjectgetRoot(){returnroot;}

publicObjectgetChild(Objectparent,intindex){

if(parent==getRoot())returnrootFiles[index];

if(parentinstanceofFile){

Filepf=(File)parent;

returnpf.listFiles(dirFilter)[index];

}

returnnull;

}

publicintgetChildCount(Objectparent){

if(parent==getRoot())returnrootFiles.length;

if(parentinstanceofFile){

Filepf=(File)parent;

File[]fs=pf.listFiles(dirFilter);

returnfs==null?0:fs.length;

}

return0;

}

publicbooleanisLeaf(Objectnode){returnfalse;}

publicvoidvalueForPathChanged(TreePathpath,ObjectnewValue){}

(TreeModelListenerl){}

(TreeModelListenerl){}

publicintgetIndexOfChild(Objectparent,Objectchild){

if(parent==getRoot()){

for(inti=0,j=rootFiles.length;i<j;i++)

if(rootFiles[i]==child)returni;

}

if(parentinstanceofFile){

Filepf=(File)parent;

File[]fs=pf.listFiles(dirFilter);

for(inti=0,j=fs.length;i<j;i++){

if(fs[i].equals(child))returni;

}

}

return-1;

}

}

{

publicintgetRowCount(){returndir==null||dir.isFile()?0:dir.listFiles().length;}

publicintgetColumnCount(){return3;}

privateFiledir;

privatevoidsetDir(Filedir){

this.dir=dir;

fireTableDataChanged();

}

publicClass<?>getColumnClass(intcolumnIndex){

switch(columnIndex){

case0:returnFile.class;

case1:returnInteger.class;

case2:returnCalendar.class;

default:returnString.class;

}

}

publicStringgetColumnName(intcolumn){

switch(column){

case0:return"名稱";

case1:return"大小";

case2:return"修改日期";

default:return"";

}

}

publicObjectgetValueAt(introwIndex,intcolumnIndex){

File[]fs=dir.listFiles();

Filef=fs[rowIndex];

switch(columnIndex){

case0:returnf;

case1:

if(f.isDirectory())returnnull;

try{

if(f.canRead())

returnnewFileInputStream(f).available();

}catch(IOExceptione){

e.printStackTrace();

}

case2:

Calendarcl=Calendar.getInstance();

cl.setTimeInMillis(f.lastModified());

returncl;

}

returnnull;

}

}

privateclass_{

publicvoidvalueChanged(TreeSelectionEvente){

TreePathpath=e.getNewLeadSelectionPath();

if(path!=null){

Objectobj=path.getLastPathComponent();

if(objinstanceofFile){

Filef=(File)obj;

File[]fs=f.listFiles();

statusLabel.setText(fs==null?null:MessageFormat.format("{0}個文件",fs.length));

}

else

statusLabel.setText(null);

}

}

}

{

publicbooleanisOpaque(){returntrue;}

(JTreetree,Objectvalue,booleanselected,booleanexpanded,booleanleaf,introw,booleanhasFocus){

if(valueinstanceofFile){

Strings=((File)value).getName();

setText(s.isEmpty()?value.toString():s);

}

else

setText(value.toString());

setForeground(selected?Color.BLUE:Color.BLACK);

setBackground(selected?Color.YELLOW:Color.WHITE);

returnthis;

}

}

{

publicvoidvalueChanged(TreeSelectionEvente){

Objectobj=e.getNewLeadSelectionPath().getLastPathComponent();

if(objinstanceofFile){

tableModel.setDir((File)obj);

}

}

}

,MouseListener{

privateJTreetree;

(JTreet){tree=t;}

privatevoidaction(InputEvente){

if(einstanceofMouseEvent){

}

if(einstanceofKeyEvent){

}

}

privatevoidexpand(Filef){

if(f.isDirectory()){

ArrayList<File>L=newArrayList<File>();

L.add(f);

FileparentFile=f.getParentFile();

while(parentFile!=null){

L.add(parentFile);

parentFile=parentFile.getParentFile();

}

TreePathtreePath=newTreePath(FileTreeModel.root);

for(inti=L.size()-1;i>-1;i--){

treePath=treePath.pathByAddingChild(L.get(i));

}

tree.setSelectionPath(treePath);

}

}

publicvoidkeyTyped(KeyEvente){}

publicvoidkeyPressed(KeyEvente){

if(e.getKeyCode()!=KeyEvent.VK_ENTER)return;

if(e.getSource()==detailTable){

introw=detailTable.getSelectedRow();

if(row!=-1){

Filef=(File)detailTable.getValueAt(row,0);

expand(f);

}

}

}

publicvoidkeyReleased(KeyEvente){

}

publicvoidmouseClicked(MouseEvente){

if(e.getClickCount()==2){

if(e.getSource()==detailTable){

introw=detailTable.getSelectedRow();

if(row!=-1){

Filef=(File)detailTable.getValueAt(row,0);

expand(f);

}

}

}

}

publicvoidmousePressed(MouseEvente){

}

publicvoidmouseReleased(MouseEvente){

}

publicvoidmouseEntered(MouseEvente){

}

publicvoidmouseExited(MouseEvente){

}

}

}

『陸』 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);
}
}
}
}

『柒』 關於web工程中java類如何獲取webapp路徑下的文件

第一復步: 先獲得classpath路徑制

Stringclasspath=this.getClass().getResource("/").getPath().replaceFirst("/","");

這樣子可以得到classpath路徑,類似於:

F:/projects/JavaStudyParent/study-springmvc-junit-test/target/springmvc-junit-test/WEB-INF/classes/


然後把WEB-INF/classes截取就能獲得WebAPP目錄啦:

StringwebappRoot=classpath.replaceAll("WEB-INF/classes/","");

得到的結果就是:

F:/projects/JavaStudyParent/study-springmvc-junit-test/target/springmvc-junit-test/


通過這個路徑你就能獲取該文件夾下的所有文件啦

『捌』 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查詢當前路徑下的文件相關的資料

熱點內容
painter2015視頻教程 瀏覽:204
jsperror 瀏覽:183
網路到底怎麼賺錢 瀏覽:402
蘋果耳機插口接觸不良 瀏覽:934
運動手環app哪個好 瀏覽:854
java設置double精度 瀏覽:587
java代碼分享網站 瀏覽:321
ps怎麼復制到文件裡面 瀏覽:360
win7管理員指紋登錄密碼忘了怎麼辦 瀏覽:38
c是一次性插入多少條數據 瀏覽:928
u盤文件編輯軟體 瀏覽:767
vb如何打開pdf文件 瀏覽:351
soundlinkiii升級 瀏覽:64
如何把文件改成cad 瀏覽:676
如何把多個監控合在一個網路內 瀏覽:637
qq的頭像在哪個文件夾 瀏覽:468
linuxexfat補丁 瀏覽:582
excelvb編程怎麼輸出數 瀏覽:737
567位qq 瀏覽:172
qq網名女生傷感 瀏覽:292

友情鏈接