FileInputStream/FileOutputStream的应用
}
}
}
//线程读
class Receiver extends Thread
{
PipedInputStream pis;
File file;
//构造方法
Receiver(PipedInputStream pis, String fileName)
{
this.pis=pis;
file=new File(fileName);
}
//线程运行
public void run()
{
try
{
//写文件流对象
FileOutputStream fs=new FileOutputStream(file);
int data;
//从管道末端读
while((data=pis.read())!=-1)
{
//写入本地文件
fs.write(data);
}
pis.close();
}
catch(IOException e)
{
System.out.println("Receiver Error" +e);
}
}
}
七、随机文件读写:RandomAccessFile类
它直接继承于Object类而非InputStream/OutputStream类,从而可以实现读写文件中任何位置中的数据(只需要改变文件的读写位置的指针)。
编程步骤:
① 生成流对象并且指明读写类型;
② 移动读写位置;
③ 读写文件内容;
④ 关闭文件。
另外由于RandomAccessFile类实现了DataOutput与DataInput接口,因而利用它可以读写Java中的不同类型的基本类型数据(比如采用readLong()方法读取长整数,而利用readInt()方法可以读出整数值等)。
程序实例:
利用随机数据流RandomAccessFile类来实现记录用户在键盘的输入,每执行一次,将用户的键盘输入存储在指定的UserInput.txt文件中。
import java.io.*;
public class RandomFileRW
{
public static void main(String args[])
{
StringBuffer buf=new StringBuffer();
char ch;
try
{
while( (ch=(char)System.in.read()) !='\n')
{
buf.append(ch);
}
//读写方式可以为"r" or "rw"
RandomAccessFile myFileStream=new RandomAccessFile("c:\\UserInput.txt","rw");
myFileStream.seek(myFileStream.length()) ;
myFileStream.writeBytes(buf.toString());
//将用户从键盘输入的内容添加到文件的尾部
myFileStream.close();
}
catch(IOException e)
{
}
}
}
八、DataInput/DataOutput接口:
实现与机器无关的各种数据格式读写(如readChar() 、readInt()、readLong()、readFloat(),而readLine()将返回一个String)。其中RandomAccessFile类实现了该接口,具有比FileInputStream或FileOutputStream类更灵活的数据读写方式。
http://www.cnblogs.com/jjtech/archive/2011/04/17/2019210.html