導航:首頁 > 編程語言 > java獲取指定路徑文件

java獲取指定路徑文件

發布時間:2022-04-02 04:22:12

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我想要寫某個文件,怎樣獲取文件的相對路徑。文件位置:

package com.hmilyld.exp;

import java.io.File;

public class ListFile {

private long[] count = new long[] ;

private File file;

private long[] listFile(String path) {
file = new File(path);
File[] f = file.listFiles();
for (int i = 0; i < f.length; i++) {
if (f[i].isDirectory()) {
count[0]++;
this.listFile(f[i].getPath());
} else {
count[1]++;
}
}
return count;
}

/**
* 得到指定路徑下的文件和文件夾數量
*
* @param path
* 要查看的路徑
* @return object[0]耗時(毫秒)<br>
* object[1]文件夾數量<br>
* object[2]文件數量
*/
public Object[] getFileCount(String path) {
long t = System.currentTimeMillis();
long[] count = this.listFile(path);
t = System.currentTimeMillis() - t;
Object[] o = new Object[] { Long.valueOf(t), Long.valueOf(count[0]),
Long.valueOf(count[1])};
return o;
}

public static void main(String[] args) {
ListFile l = new ListFile();
Object[] count = l.getFileCount("d:\\");
System.out.println(count[0]);
System.out.println(count[1]);
System.out.println(count[2]);
}
}

以前寫的一個獲取目錄下有多少文件和多少文件夾的代碼,
可以參考下.:)

⑶ java獲取某個文件夾的路徑怎麼寫

File類有兩個常用方法可以得到文件路徑一個是:getCanonicalPath(),另一個是:getAbsolutePath(),可以通過File類的實例調用這兩個方法例如file.getAbsolutePath()其中file是File的實例對象。下面是一個具體例子:
public class PathTest
{
public static void main(String[] args)
{
File file = new File(".\\src\\");
System.out.println(file.getAbsolutePath());
try
{
System.out.println(file.getCanonicalPath());
} catch (IOException e)
{
e.printStackTrace();
}
}
}
getAbsolutePath()和getCanonicalPath()的不同之處在於,getCanonicalPath()得到的是一個規范的路徑,而getAbsolutePath()是用構造File對象的路徑+當前工作目錄。例如在上面的例子中.(點號)代表當前目錄。getCanonicalPath()就會把它解析為當前目錄但是getAbsolutePath()會把它解析成為目錄名字(目錄名字是點號)。
下面是上面程序在我電腦上的輸出:
G:\xhuoj\konw\.\src\
G:\xhuoj\konw\src\

⑷ java 怎麼讀取指定路徑下所有文件名

public class GetFileName
{
public static String [] getFileName(String path)
{
File file = new File(path);
String [] fileName = file.list();
return fileName;
}
public static void getAllFileName(String path,ArrayList<String> fileName)
{
File file = new File(path);
File [] files = file.listFiles();
String [] names = file.list();
if(names != null)
fileName.addAll(Arrays.asList(names));
for(File a:files)
{
if(a.isDirectory())
{
getAllFileName(a.getAbsolutePath(),fileName);
}
}
}
public static void main(String[] args)
{
String [] fileName = getFileName("F:\\xiaoshuo");
for(String name:fileName)
{
System.out.println(name);
}
System.out.println("--------------------------------");
ArrayList<String> listFileName = new ArrayList<String>();
getAllFileName("F:\\xiaoshuo",listFileName);
for(String name:listFileName)
{
System.out.println(name);
}

}
}

⑸ java讀取指定目錄下的文件內容

publicclassReadFromFile{
/**
*以位元組為單位讀取文件,常用於讀二進制文件,如圖片、聲音、影像等文件。
*/
(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){
}
}
}
}

/**
*以字元為單位讀取文件,常用於讀文本,數字等類型的文件
*/
(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){
}
}
}
}

/**
*以行為單位讀取文件,常用於讀面向行的格式化文件
*/
(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){
}
}
}
}

/**
*隨機讀取文件內容
*/
(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){
}
}
}
}

/**
*顯示輸入流中還剩的位元組數
*/
(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實現讀取某個路徑下的文件目錄

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如何得到文件路徑

要得到什麼文件路徑``
在你要用路徑的時候 比如 <img src="XXXXXXXX"></ing>
中間的XXXXXX你就這么寫`先把原來的文件路徑用STRING 形式存在資料庫`
現在取出來`賦給變數 abc
在這里再寫成
String abc = "你的文件路徑"
<img src="<%=ABC%>"></ing>

⑻ 在java項目中如何獲取某個文件的路徑

public String getAbsolutePath()
返回抽象路徑名的絕對路徑名字元串。
如果此抽象路徑名已經是絕對路徑名,則返回該路徑名字元串,這與 getPath() 方法一樣。如果此抽象路徑名是空的抽象路徑名,則返回當前用戶目錄的路徑名字元串,該目錄由系統屬性 user.dir 指定。否則,使用與系統有關的方式分析此路徑名。在 UNIX 系統上,通過根據當前用戶目錄分析某一相對路徑名,可使該路徑名成為絕對路徑名。在 Microsoft Windows 系統上,通過由路徑名指定的當前驅動器目錄(如果有)來分析某一相對路徑名,可使該路徑名成為絕對路徑名;否則,可以根據當前用戶目錄來分析它。

返回:
絕對路徑名字元串,它與此抽象路徑名表示相同的文件或目錄的
拋出:
SecurityException - 如果無法訪問所需的系統屬性值。

public File getAbsoluteFile()
返回抽象路徑名的絕對路徑名形式。等同於 new File(this.getAbsolutePath()())。

返回:
表示與此抽象路徑名相同的文件或目錄的絕對抽象路徑名
拋出:
SecurityException - 如果無法訪問所需的系統屬性值。

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

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

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

⑼ java如何讀取指定目錄下的txt文件

importjava.io.BufferedReader;
importjava.io.FileInputStream;
importjava.io.IOException;
importjava.io.InputStreamReader;
importjava.util.Scanner;
publicclassTestRead{
publicstaticvoidmain(String[]args)throwsIOException{

Stringuri="d:123.txt"

FileInputStreamfis=newFileInputStream(uri);
InputStreamReaderisr=newInputStreamReader(fis);
BufferedReaderbr=newBufferedReader(isr);
Strings;
while((s=br.readLine())!=null){
//每次讀取一行
}
}
}

⑽ java如何獲取指定路徑下的直接下級文件目錄,而非所有的下級文件目錄

File file = new File("指定目錄");
File[] files = file.listFiles();
for(File fileIn : files){
if(fileIn.isDirectory()){
System.out.println(fileIn.getPath());
}
}

閱讀全文

與java獲取指定路徑文件相關的資料

熱點內容
優信二手車解壓後過戶 瀏覽:61
Windows常用c編譯器 瀏覽:778
關於改善國家網路安全的行政命令 瀏覽:833
安卓如何下載網易荒野pc服 瀏覽:654
javainetaddress 瀏覽:104
蘋果4s固件下載完了怎麼解壓 瀏覽:1002
命令zpa 瀏覽:285
python編譯器小程序 瀏覽:944
在app上看視頻怎麼光線調暗 瀏覽:540
可以中文解壓的解壓軟體 瀏覽:592
安卓卸載組件應用怎麼安裝 瀏覽:913
使用面向對象編程的方式 瀏覽:339
程序員項目經理的年終總結範文 瀏覽:929
內衣的加密設計用來幹嘛的 瀏覽:432
淮安數據加密 瀏覽:292
魔高一丈指標源碼 瀏覽:982
松下php研究所 瀏覽:168
c回調java 瀏覽:399
夢幻端游長安地圖互通源碼 瀏覽:745
電腦本地文件如何上傳伺服器 瀏覽:313