java文件与流_Java文件和流深入
1.什么是數(shù)據(jù)流?
數(shù)據(jù)流是指所有的數(shù)據(jù)通信通道。有兩類流,InputStream and OutputStream,Java中每一種流的基本功能依賴于它們。InputStream用于read,OutputStream用于write,讀 和寫都是相對于內(nèi)存說的,讀就是從其他地方把數(shù)據(jù)拿進(jìn)內(nèi)存,寫就是把數(shù)據(jù)從內(nèi)存推出去。這兩個(gè)都是抽象類,不能直接使用。
2.InputStream的方法有:
read()從流中讀入數(shù)據(jù)有3種方式:
◆int read() 一次讀一個(gè)字節(jié)
◆int read(byte[]) 讀多個(gè)字節(jié)到數(shù)組中
◆int read(byte[],int off,int len) 指定從數(shù)組的哪里開始,讀多長
◆skip() 跳過流中若干字節(jié)
◆available() 返回流中可用字節(jié)數(shù),但基于網(wǎng)絡(luò)時(shí)無效,返回0
◆markSupported() 判斷是否支持標(biāo)記與復(fù)位操作
◆mark() 在流中標(biāo)記一個(gè)位置,要與markSupported()連用
◆reset() 返回標(biāo)記過的位置
◆close() 關(guān)閉流
3.OutputStream的方法:
◆write(int)寫一個(gè)字節(jié)到流中
◆write(byte[])將數(shù)組中的內(nèi)容寫到流中
◆write(byte[],int off,int len)將數(shù)組中從off指定的位置開始len長度的數(shù)據(jù)寫到流中
◆close()關(guān)閉流
◆flush()將緩沖區(qū)中的數(shù)據(jù)強(qiáng)制輸出
4.File類
File可以表示文件也可以表示目錄,File類控制所有硬盤操作。
構(gòu)造器:
◆File(File parent,String child) 用父類和文件名構(gòu)造
◆File(String pathname) 用絕對路徑構(gòu)造
◆File(String parent,String child) 用父目錄和文件名構(gòu)造
◆File(URI uri) 用遠(yuǎn)程文件構(gòu)造
常用方法:
boolean createNewFile();
boolean exists();
例子:
//建立 test.txt 文件對象,判斷是否存在,不存在就創(chuàng)建
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.println("exists");
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
boolean mkdir()/mkdirs()
boolean renameTo(File destination)
例子:
//看一下這 mkdir()/mkdirs() 的區(qū)別和 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 文件,但我們?nèi)匀豢梢圆僮?#xff0c;因?yàn)槲覀儎?chuàng)建了他們的對象,是對對象進(jìn)行操作
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();
}
}
}
String list[] //顯示目錄下所有文件
long lastModified() //返回 1970.1.1 到最后修改時(shí)間的秒數(shù)
boolean isDirectory()
例子:
//列出目錄下的所有文件和目錄,最后修改時(shí)間,是目錄的后面標(biāo)出
import java.io.*;
import java.util.*;
public class Dir
{
public static void main(String args[])
{
File f=new File("Dir");
String[] listAll=null;
File temp=null;
try
{
listAll=f.list();
for(int i=0;i
{
temp=new File(listAll);
System.out.print(listAll+"\t");
if(temp.isDirectory())
{
System.out.print("\t
}
else
{
System.out.print(temp.length()+"\t");
}
System.out.println(new Date(temp.lastModified()));
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
5.文件流的建立
File f=new File("temp.txt");
FileInputStream in=new FileInputStream(f);
FileOutputStream out=new FileOutputStream(f);
例子:文件拷貝
import java.io.*;
public class Copy
{
public static void main(String args[])
{
FileInputStream fis=null;
FileOutputStream fos=null;
try
{
fis=new FileInputStream("c2.gif");
fos=new FileOutputStream("c2_copy.gif");
int c;
while((c=fis.read()) != -1)
{
fos.write(c);
}
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
if(fis != null) try{ fis.close(); }catch(Exception e){ e.printStackTrace(); }
if(fos!= null) try{ fos.close(); }catch(Exception e){ e.printStackTrace(); }
}
}
}
6.緩沖區(qū)流
BufferedInputStream
BufferedOutputStream
他們是在普通文件流上加了緩沖的功能,所以構(gòu)造他們時(shí)要先構(gòu)造普通流。
例子:文件拷貝的緩沖改進(jìn)
import java.io.*;
public class Copy
{
public static void main(String args[])
{
BufferedInputStream bis=null;
BufferedOutputStream bos=null;
byte buf[]=new byte[100];
try
{
bis=new BufferedInputStream(new FileInputStream("persia.mp3"));
bos=new BufferedOutputStream(new FileOutputStream("persia_copy.mp3"));
int len=0;
while( true )
{
len=bis.read(buf);
if(len<=0)
{
break;
}
bos.write(buf,0,len);
}
bos.flush();//緩沖區(qū)只有滿時(shí)才會將數(shù)據(jù)輸出到輸出流,用flush()將未滿的緩沖區(qū)中數(shù)據(jù)強(qiáng)制輸出
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
if(bis != null) try{ bis.close(); }catch(Exception e){ e.printStackTrace(); }
if(bos!= null) try{ bos.close(); }catch(Exception e){ e.printStackTrace(); }
}
}
}
7.原始型數(shù)據(jù)流
DataInputStream
DataOutputStream
他們是在普通流上加了讀寫原始型數(shù)據(jù)的功能,所以構(gòu)造他們時(shí)要先構(gòu)造普通流。
方法:
readBoolean()/writeBoolean()
readByte()/writeByte()
readChar()/writeByte()
......
例子:
//這個(gè)流比較簡單,要注意的就是讀時(shí)的順序要和寫時(shí)的一樣
import java.io.*;
public class DataOut{
public static void main(String args[])
{
DataOutputStream dos=null;
try
{
dos=new DataOutputStream(new FileOutputStream("dataout.txt"));
dos.writeInt(1);
dos.writeBoolean(true);
dos.writeLong(100L);
dos.writeChar('a');
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
if(dos!=null)
{
try
{
dos.close();
}
catch(Exception e)
{
}
}
}
}
}
import java.io.*;
public class DataIn
{
public static void main(String args[])
{
DataInputStream dis=null;
try
{
dis=new DataInputStream(new FileInputStream("dataout.txt"));
System.out.println(dis.readInt());
System.out.println(dis.readBoolean());
System.out.println(dis.readLong());
System.out.println(dis.readChar());
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
if(dis!=null)
{
try
{
dis.close();
}
catch(Exception e)
{
}
}
}
}
}
8.對象流
串行化:對象通過寫出描述自己狀態(tài)的數(shù)值來記述自己的過程叫串行話。
對象流:能夠輸入輸出對象的流。
將串行化的對象通過對象流寫入文件或傳送到其他地方。
對象流是在普通流上加了傳輸對象的功能,所以構(gòu)造對象流時(shí)要先構(gòu)造普通文件流。
注意:只有實(shí)現(xiàn)了Serializable接口的類才能被串行化
例子:
import java.io.*;
class Student implements Serializable
{
private String name;
private int age;
public Student(String name,int age)
{
this.name=name;
this.age=age;
}
public void greeting()
{
System.out.println("hello ,my name is "+name);
}
public String toString()
{
return "Student["+name+","+age+"]";
}
}
public class ObjectOutTest
{
public static void main(String args[])
{
ObjectOutputStream oos=null;
try
{
oos=new ObjectOutputStream(
new FileOutputStream("student.txt"));
Student s1=new Student("Jerry",24);
Student s2=new Student("Andy",33);
oos.writeObject(s1);
oos.writeObject(s2);
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
if(oos!=null)
try
{
oos.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
}
import java.io.*;
public class ObjectInTest
{
public static void main(String args[])
{
ObjectInputStream ois=null;
Student s=null;
try
{
ois=new ObjectInputStream(
new FileInputStream("student.txt"));
System.out.println("--------------------");
s=(Student)ois.readObject();
System.out.println(s);
s.greeting();
System.out.println("--------------------");
s=(Student)ois.readObject();
System.out.println(s);
s.greeting();
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
if(ois!=null)
{
try
{
ois.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
}
}
9.字符流InputStreamReader/OutputStreamWriter
上面的幾種流的單位是byte,所以叫做字節(jié)流,寫入文件的都是二進(jìn)制字節(jié),我們無法直接看,下面要學(xué)習(xí)的是字節(jié)流。
Java采用Unicode字符集,每個(gè)字符和漢字都采用2個(gè)字節(jié)進(jìn)行編碼,ASCII碼是Unicode編碼的自集InputStreamReader是字節(jié)流到字符橋的橋梁(byte->char讀取字節(jié)然后用特定字符集編碼成字符)。
OutputStreamWriter是字符流到字節(jié)流的橋梁(char->byte)。
他們是在字節(jié)流的基礎(chǔ)上加了橋梁作用,所以構(gòu)造他們時(shí)要先構(gòu)造普通文件流。
我們常用的是:
BufferedReader方法:readLine()
PrintWriter方法:println()
例子:
import java.io.*;
public class PrintWriterTest
{
public static void main(String args[])
{
PrintWriter pw=null;
try
{
pw=new PrintWriter(
new OutputStreamWriter(
new FileOutputStream("bufferedwriter.txt")));
pw.println("hello world");
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
if(pw!=null)
{
try
{
pw.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
}
}
import java.io.*;
public class BufferedReaderTest
{
public static void main(String args[])
{
BufferedReader br=null;
try
{
br=new BufferedReader(
new InputStreamReader(
new FileInputStream("bufferedwriter.txt")));
System.out.println(br.readLine());
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
if(br!=null)
{
try
{
br.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
}
}
10.隨機(jī)存取文件RandomAccessFile
可同時(shí)完成讀寫操作
支持隨機(jī)文件操作的方法:
readXXX()/writeXXX()
seek()將指針調(diào)到所需位置
getFilePointer()返回指針當(dāng)前位置
length()返回文件長度
例子:
把若干個(gè)32位的整數(shù)寫到一個(gè)名為“temp.txt”的文件中,然后利用seek方法,以相反的順序再讀取這些數(shù)據(jù)。
import java.io.*;
public class RandomFile
{
public static void main(String args[])
{
RandomAccessFile raf=null;
int data[]={12,31,56,23,27,1,43,65,4,99};
try
{
raf=new RandomAccessFile("temp.txt","rw");
for(int i=0;i
raf.writeInt(data);
for(int i=data.length-1;i>=0;i--)
{
raf.seek(i*4);
System.out.println(raf.readInt());
}
}
catch(Exception e)
{
e.getMessage();
}
finally
{
if(raf!=null)
{
try
{
raf.close();
}
catch(Exception e)
{
e.getMessage();
}
}
}
}
}
11.小結(jié)
這部分的難點(diǎn)就是類比較復(fù)雜,尤其是每個(gè)類的構(gòu)造方式,我認(rèn)為記住下面這個(gè)圖比記類的繼承關(guān)系更好些。
a.字節(jié)流:
InputStream
|-- FileInputStream (基本文件流)
|-- BufferedInputStream
|-- DataInputStream
|-- ObjectInputStream
OutputStream 同上圖
BufferedInputStream DataInputStream ObjectInputStream只是在FileInputStream上增添了相應(yīng)的功能,構(gòu)造時(shí)先構(gòu)造FileInputStream。
b.字符流:
Reader
|-- InputStreamReader (byte->char 橋梁)
|-- BufferedReader (常用)
Writer
|-- OutputStreamWriter (char->byte 橋梁)
|-- BufferedWriter
|-- PrintWriter (常用)
c. 隨機(jī)存取文件RandomAccessFile
總結(jié)
以上是生活随笔為你收集整理的java文件与流_Java文件和流深入的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java finally的作用_java
- 下一篇: java读取dat_使用在eclipse