java讀取文件目錄
㈠ java如何讀取指定目錄下的txt文件
你好代碼如下,我調試通過了,希望我的回答對你有幫助!
代碼說明,要查詢是否存在''java"。在D:盤建一個word.txt的文檔,裡面寫一些單詞,保存。運行如下代碼會判斷是否存在「java」這個單詞。
packaget;
importjava.io.BufferedReader;
importjava.io.FileInputStream;
importjava.io.FileNotFoundException;
importjava.io.IOException;
importjava.io.InputStreamReader;
publicclassTestRead{
publicstaticvoidmain(String[]args)throwsIOException{
FileInputStreamfis=newFileInputStream("d:/word.txt");
InputStreamReaderisr=newInputStreamReader(fis);
BufferedReaderbr=newBufferedReader(isr);
Strings;
intcount=0;
while((s=br.readLine())!=null){
String[]s1=s.split("");
for(inti=0;i<s1.length;i++){
if("java".equals(s1[i])){
System.out.println("存在單詞"+s1[i]);
count++;
}
}
}
if(count==0){
System.out.println("不存在java這個單詞");
}
}
}
㈡ java中在怎麼讀取文件夾中的內容
以下java程序的作用是將當前目錄及其子目錄中的.java文件收集到collection.txt文件中,並添加行號,你可以參考一下。
import java.io.*;
public class Collection
{
public static void main(String[] args) throws Exception
{
final String F=".\\collection.txt";
FW=new FileWriter(new File(F));
Collection.ProcessDirectory(new File("."));
Collection.FW.flush();
Collection.FW.close();
}
private static void ProcessDirectory(File d) throws Exception
{
File[] ds=null;
Collection.ProcessJavaFile(d);
ds=d.listFiles(Collection.DFilter);
for(int i=0;i<ds.length;i++)
{
Collection.ProcessDirectory(ds[i]);
}
}
private static void ProcessJavaFile(File d) throws Exception
{
String line=null;
LineNumberReader lnr=null;
File[] fs=d.listFiles(Collection.FNFilter);
for(int i=0;i<fs.length;i++)
{
lnr=new LineNumberReader(new FileReader(fs[i]));
Collection.FW.write(fs[i].getCanonicalPath()+"\r\n");
System.out.println(fs[i].getCanonicalPath());
while(null!=(line=lnr.readLine()))
{
Collection.FW.write(""+lnr.getLineNumber()+" "+line+"\r\n");
System.out.println(""+lnr.getLineNumber()+" "+line);
}
Collection.FW.write("\r\n");
System.out.println();
}
}
private static FileWriter FW;
private static FilenameFilter FNFilter=new FilenameFilter()
{
public boolean accept(File dir,String name)
{
return name.endsWith(".java");
}
};
private static FileFilter DFilter=new FileFilter()
{
public boolean accept(File pathname)
{
return pathname.isDirectory();
}
};
}
㈢ Java遞歸法讀取文件目錄
importjava.io.File;
publicclass${
publicstaticvoidmain(String[]args){
Stringpath="D:/";
test(path);
}
privatestaticvoidtest(Stringpath){
Filef=newFile(path);
File[]fs=f.listFiles();
if(fs==null){
return;
}
for(Filefile:fs){
if(file.isFile()){
System.out.println(file.getPath());
}else{
test(file.getPath());
}
}
}
}
㈣ 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怎麼循環讀取目錄下的文件內容
JAVA 遍歷文件夾下的所有文件(遞歸調用和非遞歸調用)
1.不使用遞歸的方法調用。
public void traverseFolder1(String path) {
int fileNum = 0, folderNum = 0;
File file = new File(path);
if (file.exists()) {
LinkedList<File> list = new LinkedList<File>();
File[] files = file.listFiles();
for (File file2 : files) {
if (file2.isDirectory()) {
System.out.println("文件夾:" + file2.getAbsolutePath());
list.add(file2);
fileNum++;
} else {
System.out.println("文件:" + file2.getAbsolutePath());
folderNum++;
}
}
File temp_file;
while (!list.isEmpty()) {
temp_file = list.removeFirst();
files = temp_file.listFiles();
for (File file2 : files) {
if (file2.isDirectory()) {
System.out.println("文件夾:" + file2.getAbsolutePath());
list.add(file2);
fileNum++;
} else {
System.out.println("文件:" + file2.getAbsolutePath());
folderNum++;
}
}
}
} else {
System.out.println("文件不存在!");
}
System.out.println("文件夾共有:" + folderNum + ",文件共有:" + fileNum);
}
2.使用遞歸的方法調用
public static List<File> getFileList(String strPath) {
File dir = new File(strPath);
File[] files = dir.listFiles(); // 該文件目錄下文件全部放入數組
if (files != null) {
for (int i = 0; i < files.length; i++) {
String fileName = files[i].getName();
if (files[i].isDirectory()) { // 判斷是文件還是文件夾
getFileList(files[i].getAbsolutePath()); // 獲取文件絕對路徑
} else if (fileName.endsWith("avi")) { // 判斷文件名是否以.avi結尾
String strFileName = files[i].getAbsolutePath();
System.out.println("---" + strFileName);
filelist.add(files[i]);
} else {
continue;
}
}
}
return filelist;
}
㈥ 如何查看java讀取文件的路徑
File類有兩個常用方法可以得到文件路徑一個是:Path(),另一個是:getAbsolutePath(),可以通過File類的實例調用這兩個方法例如file.getAbsolutePath()其中file是File的實例對象。下面是一個具體例子:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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 如何讀取目錄下的文件內容
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讀取文件路徑
你的頭是e://tttt11.PNG不是e://tttt11//1.PNG???
如果頭是e://tttt11//1.PNG,filepath沒有用,去掉。
這段這么改:
for (i=0; i <= str.length(); i += 2) {
if (i == str.length() - 1 || i == str.length() - 2)
break;
else
fileName = str.substring(i);
}
// System.out.println(filePath);
if(ii!=100)
fileName = str.substring(i);
...........後面不改回.
如果頭是e://tttt11.PNG,那這個和下面的循環規答律不一樣,大概寫下:
if(ii==1)filePath=".PNG";
把我上面修改後的代碼加到else里就行了(用我上面修改後的代碼,不然你的尾還是顯不出來).
㈨ 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讀取本地文件路徑怎麼寫
構造File對象,使用File對象取上級目錄,再取絕專對路屬徑 File f = new File("c:\\temp\\01\\1.txt"); if(f.exists()){ System.out.println(f.getParentFile().getAbsolutePath()); }