java I/O系統的類實在是太多了,這里我們只學習一些基本的和常用的,相信能夠把握這些就可以解決我們以后的普通應用了
1.什么是數據流 ?
數據流是指所有的數據通信通道
有兩類流,InputStream and OutputStream,Java中每一種流的基本功能依靠于它們
InputStream 用于read,OutputStream 用于write, 讀和寫都是相對與內存說的,讀就是從其他地方把數據拿進內存,寫就是把數據從內存推出去
這兩個都是抽象類,不能直接使用
2.InputStream 的方法有:
read() 從流中讀入數據 有3中方式:
int read() 一次讀一個字節
int read(byte[]) 讀多個字節到數組中
int read(byte[],int off,int len) 指定從數組的哪里開始,讀多長
skip() 跳過流中若干字節
available() 返回流中可用字節數,但基于網絡時無效,返回0
markSupported() 判定是否支持標記與復位操作
mark() 在流中標記一個位置,要與markSupported()連用
reset() 返回標記過的位置
close() 關閉流
3.OutputStream 的方法:
write(int) 寫一個字節到流中
write(byte[]) 將數組中的內容寫到流中
write(byte[],int off,int len) 將數組中從off指定的位置開始len長度的數據寫到流中
close() 關閉流
flush() 將緩沖區中的數據強制輸出
4.File 類
File 可以表示文件也可以表示目錄,File 類控制所有硬盤操作
構造器:
File(File parent,String child) 用父類和文件名構造
File(String pathname) 用絕對路徑構造
File(String parent,String child) 用父目錄和文件名構造
File(URI uri) 用遠程文件構造
常用方法:
boolean createNewFile();
boolean exists();
例子:
//建立 test.txt 文件對象,判定是否存在,不存在就創建
import java.io.*;
public class CreateNewFile{
public static void main(String args[]){
File f=new File("test.txt");
try{
if(!f.exists())
f.createNewFile();
else
System.out.}catch(Exception e){
e.printStackTrace();
}
}
}
boolean mkdir()/mkdirs()
boolean renameTo(File destination)
例子://看一下這 mkdir()/mkdirs() 的區別和 renameTo 的用法
import java.io.*;
public class CreateDir{
public static void main(String args[]){
File f=new File("test.txt");
File f1=new File("Dir");
File f2=new File("Top/Bottom");
File f3=new File("newTest.txt");
try{
f.renameTo(f3);
f1.mkdir();
f2.mkdirs();
}catch(Exception e){
e.printStackTrace();
}
}
}
String getPath()/getAbsolutePath()
String getParent()/getName()
例子://硬盤上并沒有parent 目錄和 test.txt 文件,但我們仍然可以操作,因為我們創建了他們的對象,是對對象進行操作
import java.io.*;
public class Test{
public static void main(String args[]){
File f=new File("parent/test.txt");
File f1=new File("newTest.txt");
try{
System.out.println(f.getParent());
System.out.println(f.getName());
System.out.println(f1.getPath());
System.out.println(f1.getAbsolutePath());
}catch(Exception e){
e.printStackTrace();
}
}
}
新聞熱點
疑難解答