java ioc语言读入dat文件件并写入数据库

好好学习,天天向上
读写dat文件
import java.io.FileNotFoundE
import java.io.IOE
import java.io.RandomAccessF
public class Test {
public static void main(String[] args) throws IOException {
RandomAccessFile file1 =
int b[] = {23,33,444333};
String s = "";
file1 = new RandomAccessFile("c:/1.dat","rw");
for (int i=0;i&b.i++){
file1.writeInt(b[i]);
for(int i=b.length-1;i&=0;i--){
file1.seek(i*4);
System.out.println(file1.readInt());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
file1.close();
正序写入,逆序写出。
没有更多推荐了,
加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!在线求救:java从.dat文件中读取数据
[问题点数:100分,结帖人u]
本版专家分:0
结帖率 33.33%
CSDN今日推荐
本版专家分:28331
本版专家分:46580
2015年7月 Java大版内专家分月排行榜第一2015年6月 Java大版内专家分月排行榜第一2011年2月 Java大版内专家分月排行榜第一
2015年5月 Java大版内专家分月排行榜第二2013年5月 Java大版内专家分月排行榜第二
2011年5月 Java大版内专家分月排行榜第三2011年1月 Java大版内专家分月排行榜第三
本版专家分:28331
本版专家分:0
结帖率 33.33%
本版专家分:0
结帖率 33.33%
本版专家分:0
结帖率 33.33%
匿名用户不能发表回复!|
CSDN今日推荐技术闷骚男
java 对象存储为dat文件
先说下为什么我们要将对象存储起来。使用缓存机制不仅可以为用户节省流量,同时还可以给用户带来好的用户体验。
class MyBean implements Serializable {
private static final long serialVersionUID = 1L;
private boolean myB
private String myS
private Vector&String& myV
public MyBean() {
public boolean isMyBoolean() {
return myB
public void setMyBoolean(boolean myBoolean) {
this.myBoolean = myB
public String getMyString() {
return myS
public void setMyString(String myString) {
this.myString = myS
public Vector&String& getMyVector() {
return myV
public void setMyVector(Vector&String& myVector) {
this.myVector = myV
存储的对象一定要继承Serializable接口序列化
为什么要序列化对象:
在没有序列化前,每个保存在堆(Heap)中的对象都有相应的状态(state),即实例变量(instance ariable)比如:
MyBean myFoo = new
MyBean ();
myFoo .setString(“37”);
myFoo.setMyBoolean(true);
当通过下面的代码序列化之后,MyFoo对象中的width和Height实例变量的值(37,true)都被保存到foo.ser文件中,这样以后又可以把它 从文件中读出来,重新在堆中创建原来的对象。当然保存时候不仅仅是保存对象的实例变量的值,JVM还要保存一些小量信息,比如类的类型等以便恢复原来的对 象。
public static void main(String[] args) throws Exception {
MyBean mb = new MyBean();
mb.setMyBoolean(true);
mb.setMyString("xml is cool");
Vector&String& v = new Vector&String&();
v.add("one");
v.add("two");
v.add("three");
mb.setMyVector(v);
String fileString = "D:/a.dat";
ObjectDatUtil.object2Dat(mb, fileString);
MyBean tt = ObjectDatUtil.dat2Object(fileString,MyBean.class);
Vector&String& vector = (Vector&String&) tt.getMyVector();
System.out.println(vector.toString());
System.out.println(tt.getMyString());
System.out.println(tt.isMyBoolean());
public class ObjectDatUtil {
private static ObjectDatUtil objectDatUtil =
private ObjectDatUtil() {
public ObjectDatUtil getInstance() {
if (objectDatUtil == null) {
objectDatUtil = new ObjectDatUtil();
return objectDatU
* 将对象转换为DAT文件存储
* @param object
要存储的对象
* @param filePath
带完全的保存路径的文件名
* @throws FileNotFoundException
* @throws IOException
* @throws Exception
public static void object2Dat(Object object, String fileName)
throws FileNotFoundException, IOException, Exception {
// 创建输出文件
File fo = new File(fileName);
// 文件不存在,就创建该文件
if (!fo.exists()) {
// 先创建文件的目录
String path = fileName.substring(0, fileName.lastIndexOf('.'));
File pFile = new File(path);
pFile.mkdirs();
FileOutputStream fs = new FileOutputStream(fileName);
ObjectOutputStream oo = new ObjectOutputStream(fs);
oo.writeObject(object);
oo.flush();
oo.close();
fs.close();
* 将DAT文件转换为object对象
* @param objSource
DAT文件路径
* @return 返回对象
* @throws IOException
@SuppressWarnings("unchecked")
public static &T& T dat2Object(String objSource, Class&T& class1) {
T object =
FileInputStream fi =
ObjectInputStream oi =
fi = new FileInputStream(objSource);
oi = new ObjectInputStream(fi);
object = (T)oi.readObject();
} catch (Exception e) {
e.printStackTrace();
} finally {
oi.close();
fi.close();
} catch (IOException e) {
e.printStackTrace();
没有更多推荐了,
加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!Java中一些数据流的操作
java中java.io包中包含子类最多的有“四大家族”,他们分别是InputStream,OutputStream,Reader,Writer.
1.保存字节级的流:
DataOutputStream 类
FileOutputStream 类向文件中写入数据的类。
两个类结合起来使用,代码事例
import java.io.*;
public class Simpleoutputtest
&public static void main(String []args)
&&double pi=3.1415926;
&&int i=100;
&&boolean okay=
&&char cc='x';
&&String s="2.txt";
&&String q="3.doc";
&&&FileOutputStream
fisout=new FileOutputStream("D:\\sample.dat");
&&&DataOutputStream
out=new DataOutputStream(fisout);
&&&out.writeDouble(pi);
&&&out.writeInt(i);
&&&out.writeBoolean(okay);
&&&out.writeChar(cc);
&&&out.writeUTF(s);
&&&out.writeUTF(q);
&&&out.close();&&
&&}catch(FileNotFoundException
&&&System.err.println(fe);
&&}catch(IOException ioe)
&&&System.out
.println(ioe);
读取字节流的方式和保存字节流的方式一样,只是采用了DataInputStream和FileInputStream类。
采用DataOutputStream类读取的数据与文件是独立于操作系统的。
下面采用FileInputStream类单独的读取当前系统的文件,例:
&import java.io.*;
public class FileInput
&public static void main(String[] args) throws
IOException
&&byte a[]=new byte[2056];
&&&FileInputStream
file=new FileInputStream("D:\\1.txt");
bytes=file.read(a);
str=new String(a);
&&&System.out.println(str);
&&catch(IOException e)
&&&System.out.println(e.toString()
--------------------------------------------------------------------------------------------------
想让数据读取或者存在的速度更快,可采用缓冲流类
BufferedOutputStream,下面两例子说明,采用缓冲流技术和没有采用缓冲流技术的区别,例:
没有缓冲流的例子:
import java.io.*;
public class nobuffered
&public static void main(String []args)
start=System.currentTimeMillis();
&&&FileOutputStream
xql=new FileOutputStream("E:\\Java的数据流的数据");
&&&DataOutputStream
c=new DataOutputStream(xql);
&&&for(int
i=0;i&100000;i++)
&&&&c.writeDouble(Math.random());
&&&c.close();
stop=System.currentTimeMillis();
&&&System.out.println(stop-start);
&&}catch(IOException ioe)
{ System.out.println(ioe);}
有缓冲流技术:
import java.io.*;
public class havebufftered
&public static void main(String []args)
start=System.currentTimeMillis();
&&&FileOutputStream
xql=new FileOutputStream("E:\\Java的数据流的数据");
&&&BufferedOutputStream
c=new BufferedOutputStream(xql);
&&&DataOutputStream
out=new DataOutputStream(c);
&&&for(int
i=0;i&100000;i++)
&&&&out.writeDouble(Math.random());
&&&out.close();
stop=System.currentTimeMillis();
&&&System.out.println(stop-start);
&&}catch(IOException ioe)
{ System.out.println(ioe);}
读取数据一样也可以采用缓冲流技术。
--------------------------------------------------------------------------------------------------
文件的一些操作
File类,提供了描述文件和目录的一种方法。它是Java.io包中,但不是InputStream或者Outputstream的子类,他不负责数据的输入输出,值是专门用来管理磁盘文件和目录的。
利用File类创建文件,并互相复制。例:
import java.io.*;
public class SafeCopy{
&&& public
static void copyFile(DataInputStream in,
DataOutputStream out)throws IOException{
&&&&&&&&&&&
while (true)
&&&&&&&&&&&&&&&
out.writeByte(in.readByte());
} catch(EOFException eof) {
&&&&&&&&&&&
&&& public
static void main(String args[]){
if (args.length != 2)
&&&&&&&&&&&
System.out.println("Usage: java SafeCopy sourceFile
targetFile");
&&&&&&&&&&&
String inFileName& = args[0], outFileName =
&&&&&&&&&&&
File inFile = new File(inFileName);
&&&&&&&&&&&
File outFile = new File(outFileName);
&&&&&&&&&&&
if (!inFile.exists())
&&&&&&&&&&&&&&&
System.out.println(inFileName + " does not exist.");
&&&&&&&&&&&
else if (outFile.exists())
&&&&&&&&&&&&&&&
System.out.println(outFileName + " already exists.");
&&&&&&&&&&&
&&&&&&&&&&&&&&&
&&&&&&&&&&&&&&&&&&&
DataInputStream in = new DataInputStream(
&&&&&&&&&&&&&&&&&&&&&&&
new BufferedInputStream(
&&&&&&&&&&&&&&&&&&&&&&&
new FileInputStream(inFileName)));
&&&&&&&&&&&&&&&&&&&
DataOutputStream out = new DataOutputStream(
&&&&&&&&&&&&&&&&&&&&&&&
new BufferedOutputStream(
&&&&&&&&&&&&&&&&&&&&&&&
new FileOutputStream(outFileName)));
&&&&&&&&&&&&&&&&&&&
copyFile(in, out);
&&&&&&&&&&&&&&&&&&&
in.close();
&&&&&&&&&&&&&&&&&&&
out.close();
&&&&&&&&&&&&&&&
}catch(IOException ioe) {
&&&&&&&&&&&&&&&&&&&
System.out.println("Unknown error: " + ioe);
&&&&&&&&&&&&&&&
&&&&&&&&&&&
--------------------------------------------------------------------------------------------------
操作字符数据和操作字节的类型是一样的。只是采用的类不一样,操作字符的类Reader和Writer类的子类,FileReader
BufferReader 、等
采用PrintWrite类保存字符型的数据,例:
import java.io.*;
public class SimpleCharOutputTest{
&public static void main(String args[]){
double Pi = 3.;
int i = 100000;
boolean okay =
char cc = 'J';
String s = "Java C Pascal";
FileWriter fw = new FileWriter("E:\\Java的数据流的数据");
PrintWriter out = new PrintWriter(new BufferedWriter(fw));
out.println(Pi);
out.println(i);
out.println(okay);
out.println(cc);
out.println(s);
out.close();
if (out.checkError())
&&&&&&&&&&&
System.out.println("An error has occured during output.");
}catch(IOException ioe) {
System.out.println("Error while opening the file.");
--------------------------------------------------------------------------------------------------
保存和读取对象数据,在进行对象的操作时候注意要序列化Serializable
首先序列化一个Address 类
import java.io.*;
public class Address implements Serializable
{& protected String first,
&& public Address()
&& {& first =
email = ""; }
Address(String& _first, String&
&& {& first =
&& public String toString()
&& {& return
first + " (" + email + ")"; }
然后向文件中写入对象
import java.io.*;
import java.util.*;
public class SerialWriteTest
{& public static void main(String args[])
{& ObjectOutputStream out = new
ObjectOutputStream(
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
new FileOutputStream("D:\\1.dat"));
int i = 10000;
Date now = new Date();
Address address = new Address("fxzhu", "");
out.writeInt(i);
out.writeObject(now);
out.writeObject(address);
out.close();
catch(IOException ioe)
{& System.out.println(ioe); }
再从写入对象的文件中读取
import java.io.*;
import java.util.*;
public class SerialReadTest
{& public static void main(String args[])
{& ObjectInputStream in = new
ObjectInputStream(
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
new FileInputStream("D:\\1.dat"));
int i = in.readInt();
Date date = (Date)in.readObject();
Address address = (Address)in.readObject();
in.close();
System.out.println("Integer: " + i);
System.out.println("Date: " + date);
System.out.println("Address: " + address);
catch(ClassNotFoundException cnfe)
{& System.out.println(cnfe); }
catch(IOException ioe)
{& System.out.println(ioe); }
--------------------------------------------------------------------------------------------------
&随机流RandomAccessFile类,例:
向文件中写如数据
&& import java.io.*;
&& public class RafDemo1{
public static void main(String args[]) throws IOException{
RandomAccessFile raf=new RandomAccessFile("D:\\1.txt","rw");
raf.writeBoolean(true);
raf.writeInt(168168);
raf.writeChar('i');
raf.writeDouble(168.168);
raf.writeUTF( "谢其麟");
raf.seek(1);
System.out.println(raf.readInt());
System.out.println(raf.readChar());
System.out.println(raf.readDouble());
System.out.println(raf.readUTF()& );
raf.seek(0);
System.out.println(raf.readBoolean());
raf.close();
读取文件中的数据,可以随意的定为到哪个位置开始读&&
raf.seek(position);
import java.io.*;
& class RafDemo2{
&&& public
static void main(String args[]) {
RandomAccessFile raf=new RandomAccessFile("D:\\1.txt","r");
long count=10;
long position=raf.length();
position-=
if(position&0) position=0;
raf.seek(position);
while(true)
byte a=raf.readByte() ;
System.out.print((char)a);
catch(EOFException eofe) {
}catch(Exception e) {
e.printStackTrace();
已投稿到:
以上网友发言只代表其个人观点,不代表新浪网的观点或立场。java学习笔记16--I/O流和文件_Java教程_动态网站制作指南
java学习笔记16--I/O流和文件
来源:人气:639
学习笔记16--I/O流和文件本文地址:http://www.cnblogs.com/archimedes/p/java-study-note16.html,转载请注明源地址。IO(Input Output)流IO流用来处理设备之间的数据传输,对数据的操作是通过流的方式,Java用于操作流的对象都在IO包中输入/输出流可以从以下几个方面进行分类从流的方向划分:输入流、输出流从流的分工划分:节点流、处理流从流的内容划分:面向字符的流、面向字节的流字符流和字节流字符流的由来: 因为数据编码的不同,而有了对字符进行高效操作的流对象。本质其实就是基于字节流读取时,去查了指定的码表。 字节流和字符流的区别:读写单位不同:字节流以字节(8bit)为单位,字符流以字符为单位,根据码表映射字符,一次可能读多个字节。处理对象不同:字节流能处理所有类型的数据(如图片、avi等),而字符流只能处理字符类型的数据。结论:只要是处理纯文本数据,就优先考虑使用字符流。 除此之外都使用字节流。流按流向分为:输入流、输出流IO流常用基类字节流的抽象基类:&InputStream,OutputStream。字符流的抽象基类:&Reader, Writer。注:由这四个类派生出来的子类名称都是以其父类名作为子类名的后缀。如:InputStream的子类FileInputStream。如:Reader的子类FileReader。Java流操作有关的类或接口:Java流类图结构:读写文本文件写文本文件例:在C盘根目录创建文本文件Hello.txt,并往里写入若干行文本import java.io.*;
class Ex1{
public static void main ( String[] args ) throws IOException {
//main方法中声明抛出IO异常
String fileName = "C:\\Hello.txt";
FileWriter writer = new FileWriter( fileName );
writer.write( "Hello!\n");
writer.write( "This is my first text file,\n"
writer.write( "You can see how this is done.\n" );
writer.write("输入一行中文也可以\n");
writer.close();
}}说明:每次运行这个程序,都将删除已经存在的&Hello.txt&文件,创建一个新的同名文件。FileWriter的构造方法有五个,本例是通过一个字符串指定文件名来创建。FileWriter类的write方法向文件中写入字符Writer类的流可实现内部格式到外部磁盘文件格式的转换&Hello.txt&是一个普通的ASCII码文本文件,每个英文字符占一个字节,中文字符占两个字节Java程序中的字符串则是每个字符占两个字节的,采用Unicode编码close方法清空流里的内容并关闭它。如果不调用该方法,可能系统还没有完成所有数据的写操作,程序就结束了在看一个例子:处理IO异常import java.io.*;
class Ex2 {
public static void main ( String[] args ) {
String fileName = "c:\\Hello.txt" ;
//将所有IO操作放入try块中
FileWriter writer = new FileWriter( fileName ,true );
writer.write( "Hello!\n");
writer.write( "This is my first text file,\n"
writer.write( "You can see how this is done. \n" );
writer.write("输入一行中文也可以\n");
writer.close();
catch ( IOException iox) {
System.out.intln("Problem writing" + fileName ); }
}}说明:运行此程序,会发现在原文件内容后面又追加了重复的内容,这就是将构造方法的第二个参数设为true的效果如果将文件属性改为只读属性,再运行本程序,就会出现IO错误,程序将转入catch块中,给出出错信息BufferedWriter类如果需要写入的内容很多,就应该使用更为高效的缓冲器流类BufferedWriterFileWriter和BufferedWriter类都用于输出字符流,包含的方法几乎完全一样,但BufferedWriter多提供了一个newLine()方法用于换行使用BufferedWriter完成上面的功能:import java.io.*; class Ex3 {
public static void main ( String[] args ) throws IOException
String fileName = "C:/newHello.txt" ;
BufferedWriter out = new BufferedWriter(
FileWriter( fileName ) );
out.write( "Hello!"
out.newLine() ;
out.write( "This is another text file using BufferedWriter,"
out.newLine(); ;
out.write( "So I can use a common way to start a newline" );
out.close();
}}读文本文件FileReader类从文本文件中读取字符继承自Reader抽象类的子类InputStreamReaderBufferedReader读文本文件的缓冲器类具有readLine()方法,可以对换行符进行鉴别,一行一行地读取输入流中的内容继承自Reader文件输入方法:BufferedReader in = new BufferedReader(new FileReader( fileName) );从Hello.txt中读取文本并显示在屏幕上import java.io.*;class Ex4 {
public static void main ( String[] args ) {
String fileName = "C:/Hello.txt" ,
BufferedReader in = new BufferedReader(
new FileReader( fileName
line = in.readLine();
//读取一行内容
while ( line != null ) {
System.out.println( line );
   line = in.readLine();
in.close();
catch ( IOException iox ) {
System.out.println("Problem reading " + fileName );
}}运行该程序,屏幕上将逐行显示出Hello.txt文件中的内容FileReader对象:创建后将打开文件,如果文件不存在,会抛出一个IOExceptionBufferedReader类的readLine()方法:从一个面向字符的输入流中读取一行文本。如果其中不再有数据,返回nullReader类的read()方法:也可用来判别文件结束。该方法返回的一个表示某个字符的int型整数,如果读到文件末尾,返回 -1。据此,可修改本例中的读文件部分:while((c=in.read())!= -1)
System.out.print((char)c);close()方法:为了可以更为有效地利用有限的资源,应该在读取完毕后,调用该方法指定源文件和目标文件名,将源文件的内容拷贝至目标文件。调用方式为:java copy sourceFile destinationFileclass CopyMaker {
String sourceName, destN
private boolean openFiles() {
source = new BufferedReader(new FileReader(sourceName));
} catch (IOException ex) {
System.out.println("Problem opening " + sourceName);
dest = new BufferedWriter(new FileWriter(destName));
} catch (IOException ex) {
System.out.println("Problem opening " + destName);
private boolean copyFiles() {
line = source.readLine();
while(line != null) {
dest.write(line);
dest.newLine();
line = source.readLine();
} catch (IOException ex) {
System.out.println("Problem reading or writing");
private boolean closeFiles() {
boolean retVal =
source.close();
} catch (IOException ex) {
System.out.println("Prolem closing " + sourceName);
dest.close();
} catch (IOException ex) {
System.out.println("Problem closing " + destName);
return retV
public boolean copy(String src, String dst) {
sourceName=
destName =
return openFiles() && copyFiles() && closeFiles();
}}public class CopyFile {
public static void main(String[] args) {
if(args.length == 2)
new CopyMaker().copy(args[0], args[1]);
System.out.println("Please Enter names");
}}读写二进制文件二进制文件原则上讲,所有文件都是由8位的字节组成的如果文件字节中的内容应被解释为字符,则文件被称为文本文件;如果被解释为其它含义,则文件被称为二进制文件例如文字处理程序,例如字处理软件产生的doc文件中,数据要被解释为、格式、图形和其他非字符信息。因此,这样的文件是二进制文件,不能用Reader流正确读取为什么需要二进制文件?输入输出更快比文本文件小很多有些数据不容易被表示为字符抽象类OutputStream派生类FileOutputStream用于一般目的输出(非字符输出)用于成组字节输出派生类DataOutputStream具有写各种基本数据类型的方法将数据写到另一个输出流它在所有的计算机平台上使用同样的数据格式其常用的一些方法见下表例:将三个int型数字255/0/-1写入数据文件data1.datpublic class ext6_7 {
public static void main(String[] args) {
String fileName = "c:/data1.dat";
int value0 = 255, value1 = 0, value2 = -1;
DataOutputStream out = new DataOutputStream(
new FileOutputStream(fileName));
out.writeInt(value0);
out.writeInt(value1);
out.writeInt(value2);
out.close();
} catch (IOException ex) {
System.out.println("Problem writing " + fileName);
}}说明:FileOutputStream类的构造方法负责打开文件&data1.dat&用于写数据FileOutputStream类的对象与DataOutputStream对象连接,写基本类型的数据BufferedOutputStream写二进制文件的缓冲流类类似于文本文件中的BufferedWriter对于大量数据的写入,可提高效率用法示例:DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream( fileName ) ) ); 例:向文件中写入各种数据类型的数,并统计写入的字节数public class ex6_8 {
public static void main(String[] args) throws IOException {
String fileName = "c:/mixedTypes.dat";
DataOutputStream dataOut = new DataOutputStream(
new BufferedOutputStream(
new FileOutputStream(fileName)));
dataOut.writeInt(0);
System.out.println(dataOut.size() + "bytes have been written.");
dataOut.writeDouble(31.2);
System.out.println(dataOut.size() + "bytes have been written.");
dataOut.writeBytes("java");
System.out.println(dataOut.size() + "bytes have been written.");
dataOut.close();
}}读二进制文件过滤流读或写的同时对数据进行处理通过另外一个流来构造一个过滤流大部分java.io 包所提供过滤流都是FilterInputStream和FilterOutputStream的子类:DataInputStream 和 DataOutputStreamBufferedInputStream 和 BufferedOutputStreamLineNumberInputStreamPushbackInputStreamPrintStream读取上面的例子创建的数据文件中的3个int型数字,显示相加结果public class ex6_10 {
public static void main(String[] args) {
String fileName = "C:\\data1.dat";
int sum = 0;
DataInputStream instr = new DataInputStream(
new BufferedInputStream(new FileInputStream(fileName)));
sum += instr.readInt();
sum += instr.readInt();
sum += instr.readInt();
System.out.println("The sum is: " + sum);
instr.close();
} catch (IOException ex) {
System.out.println("Problem reading " + fileName);
}}分析:readInt方法可以从输入流中读入4个字节并将其当作int型数据由于知道文件中存储的是3个int型数据,所以使用了3个读入语句如果不知道数据的个数该怎么办呢?因为DataInputStream的读入操作如遇到文件结尾就会抛出EOFException异常,所以我们可以将读操作放入try块中将读操作放入try块中,使遇到文件结尾就会抛出EOFException异常,进入到相应的catch块中try{
while(true) sum += instr.readInt();}catch ( EOFException
System.out.println("The sum is: " + sum);
instr.close();}File类表示磁盘文件信息定义了一些与平台无关的方法来操纵文件&创建、删除文件&重命名文件&判断文件的读写权限及是否存在&设置和查询文件的最近修改时间等构造文件流可以使用File类的对象作为参数File类常用方法:例:在C盘创建文件Hello.txt,如果存在则删除旧文件,不存在则直接创建新的public class ex6_13 {
public static void main(String[] args) {
File f = new
File("C:" + File.separator + "hello.txt");
if(f.exists()) {
f.delete();
f.createNewFile();
} catch (Exception e) {
System.out.println(e.getMessage());
}}处理压缩文件压缩流类&java.util.z包中提供了一些类,使我们可以以压缩格式对流进行读写&它们都继承自字节流类OutputStream和InputStream&其中GZIPOutputStream和ZipOutputStream可分别把数据压缩成GZIP格式和Zip格式&GZIPInputStream和ZipInputStream可以分别把压缩成GZIP格式或Zip的数据解压缩恢复原状public class ex6_14 {
public static void main(String[] args) throws IOException{
FileInputStream in = new FileInputStream("c:/Hello.txt");
GZIPOutputStream out = new GZIPOutputStream(
//生成压缩文件test.gz
new FileOutputStream("c:/test.gz"));
System.out.println("Writing compressing file from" +
"c:/Hello.txt to c:/test.gz");
while((c = in.read()) != -1) {
out.write(c);
in.close();
out.close();
System.out.println("Reading file form c:/test.gz to monitor");
BufferedReader in2 = new BufferedReader(
new InputStreamReader(
new GZIPInputStream(
new FileInputStream("c:/test.gz"))));
while((s = in2.readLine()) != null) System.out.println(s);
in2.close();
System.out.println("Writing decompression to c:/newHello.txt");
GZIPInputStream in3 = new GZIPInputStream(
//读取test.gz中的内容
new FileInputStream("c:/test.gz"));
FileOutputStream out2 = new FileOutputStream("c:/newHello.txt");
while((c = in3.read()) != -1) out2.write(c);
in3.close();
out2.close();
}}Zip文件&可能含有多个文件,所以有多个入口(Entry)&每个入口用一个ZipEntity对象表示,该对象的getName()方法返回文件的最初名称ZipOutputStream&父类是DeflaterOutputStream&可以把数据压缩成ZIP格式ZipInputStream&父类是InflaterInputStream&可以把压缩成ZIP格式的数据解压缩例:指定若干文件名,将所有文件压缩为"c:/test.zip",再从此压缩文件中解压缩并显示public class ex6_15 {
public static void main(String[] args) throws IOException {
ZipOutputStream out = new ZipOutputStream(
new BufferedOutputStream(
new FileOutputStream("c:/test.zip")));
String[] s = {"c:/t1.txt", "c:/t2.txt", "c:/t3.txt"};
//文件路径
for(int i = 0; i & s. i++) {
System.out.println("Writing file" + s[i]);
BufferedInputStream in = new BufferedInputStream(
new FileInputStream(s[i]));
out.putNextEntry(new ZipEntry(s[i]));
while((c = in.read()) != -1) out.write(c);
in.close();
out.close();
System.out.println("Reading file");
ZipInputStream in2 = new ZipInputStream(
new BufferedInputStream(
new FileInputStream("c:/test.zip")));
while((ze = in2.getNextEntry()) != null) {
System.out.println("Reading file " + ze.getName());
while((x = in2.read()) != -1) System.out.write(x);
System.out.println();
in2.close();
}}再看一个例子:解压缩Zip文件,并恢复其原来路径class Unzip {
byte[] doc =
//存储解压缩数据的缓冲字节数组
String FileName =
//压缩文件名字符串
String UnZipPath =
//解压缩路径字符串
public Unzip(String filename, String unZipPath) {
this.FileName =
this.UnZipPath = unZipP
this.setUnZipPath(this.UnZipPath);
public Unzip(String filename) {
this.FileName = new String(filename);
this.UnZipPath =
this.setUnZipPath(this.UnZipPath);
private void setUnZipPath(String unZipPath) {
if(unZipPath.endsWith("\\"))
this.UnZipPath = new String(unZipPath);
this.UnZipPath = new String(unZipPath + "\\");
public void doUnZip() {
ZipInputStream zipis = new ZipInputStream(
new FileInputStream(FileName));
ZipEntry fEntry =
while((fEntry = zipis.getNextEntry()) != null) {
if(fEntry.isDirectory()) {
checkFilePath(UnZipPath + fEntry.getName());
//是文件则解压缩文件
String fname = new String(UnZipPath + fEntry.getName());
FileOutputStream out = new FileOutputStream(fname);
doc = new byte[512];
while((n = zipis.read(doc, 0, 512)) != -1) {
out.write(doc, 0, n);
out.close();
} catch (Exception ex) {
zipis.close();
//关闭输入流
} catch (IOException ioe) {
System.out.println(ioe);
private void checkFilePath(String dirName) {
File dir = new File(dirName);
if(!dir.exists())
dir.mkdirs();
}}public class ex6_16 {
public static void main(String[] args) {
String zipFile = "c:/test.zip";
String unZipPath = "";
Unzip myZip = new Unzip(zipFile, unZipPath);
myZip.doUnZip();
}}对象序列化保存对象的信息,在需要的时候,再读取这个对象内存中的对象在程序结束时就会被垃圾回收机制清除用于对象信息存储和读取的输入输出流类:ObjectInputStream、ObjectOutputStream实现对象的读写通过ObjectOutputStream把对象写入磁盘文件通过ObjectInputStream把对象读入程序&不保存对象的transient和static类型的变量&对象要想实现序列化,其所属的类必须实现Serializable接口必须通过另一个流构造ObjectOutputStream:FileOutputStream out = new FileOutputStream("theTime");
ObjectOutputStream s =
new ObjectOutputStream(out);s.writeObject("Today");s.writeObject(new Date());s.flush();必须通过另一个流构造ObjectInputStream:FileInputStream in = new FileInputStream("theTime");ObjectInputStream s = new ObjectInputStream(in);String today = (String)s.readObject();Date date = (Date)s.readObject();空接口,使类的对象可实现序列化Serializable 接口的定义:package java.public interface Serializable {
// there's nothing in here!};实现Serializable接口的语句public class MyClass implements Serializable {
...}使用关键字transient可以阻止对象的某些成员被自动写入文件看一个例子:创建一个书籍对象,并把它输出到一个文件book.dat中,然后再把该对象读出来,在屏幕上显示对象信息class Book implements Serializable {
public Book(int id, String name, String author, float price) {
this.name =
this.author =
this.price =
}}public class ex6_17 {
public static void main(String[] args) throws IOException, ClassNotFoundException {
Book book = new Book(100000, "java programming", "Wu", 23);
ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream("c:/book.dat"));
oos.writeObject(book);
oos.close();
System.out.println("ID is: " + book.id);
System.out.println("name is: " + book.name);
System.out.println("author is: " + book.author);
System.out.println("price is: " + book.price);
}}Externalizable 接口&实现该接口可以控制对象的读写&API中的说明为public interface Externalizable extends Serializable&其中有两个方法writeExternal()和readExternal(),因此实现该接口的类必须实现这两个方法&ObjectOutputStream的writeObject()方法只写入对象的标识,然后调用对象所属类的writeExternal()&ObjectInputStream的readObject()方法调用对象所属类的readExternal()随机文件读写RandomFile类&可跳转到文件的任意位置读/写数据&可在随机文件中插入数据,而不破坏该文件的其他数据&实现了DataInput 和 DataOutput 接口,可使用普通的读写方法&有个位置指示器,指向当前读写处的位置。刚打开文件时,文件指示器指向文件的开头处。对文件指针显式操作的方法有:int skipBytes(int n):把文件指针向前移动指定的n个字节void seek(long):移动文件指针到指定的位置。long getFilePointer():得到当前的文件指针。&在等长记录格式文件的随机读取时有很大的优势,但仅限于操作文件,不能访问其它IO设备,如网络、内存映像等&可用来实现读和写,构造方法包括public RandomAccessFile(File file,String mode) throws FileNotFoundExceptionpublic RandomAccessFile(String name, String mode) throws FileNotFoundException&建立一个RandomAccessFile时,要指出你要执行的操作:仅从文件读,还是同时读写new RandomAccessFile("farrago.txt", "r");new RandomAccessFile("farrago.txt", "rw");RandomAccessFile类常用API例:创建一个雇员类,包括姓名、年龄。姓名不超过8个字符,年龄是int类型。每条记录固定为20个字节。使用RandomAccessFile向文件添加、修改、读取雇员信息class Employee {
char name[] = {'\u0000', '\u0000','\u0000', '\u0000',
'\u0000', '\u0000', '\u0000', '\u0000'};
public Employee(String name, int age) throws Exception {
if(name.toCharArray().length & 8)
System.arraycopy(name.toCharArray(), 0, this.name, 0, 8);
System.arraycopy(name.toCharArray(), 0, this.name, 0, name.toCharArray().length);
this.age =
}}public class ex6_18 {
String FileN
public ex6_18(String FileName) {
this.FileName = FileN
public void writeEmployee(Employee e, int n) throws Exception {
RandomAccessFile ra = new RandomAccessFile(FileName, "rw");
ra.seek(n * 20);
//将位置指示器移到指定位置上
for(int i = 0; i & 8; i++) ra.writeChar(e.name[i]);
ra.writeInt(e.age);
ra.close();
public void readEmployee(int n) throws Exception {
char buf[] = new char[8];
RandomAccessFile ra = new RandomAccessFile(FileName, "r");
ra.seek(n * 20);
for(int i = 0; i & 8; i++) buf[i] = ra.readChar();
System.out.print("name: ");
System.out.println(buf);
System.out.println("age: " + ra.readInt());
ra.close();
public static void main(String[] args) throws Exception {
ex6_18 t = new ex6_18("c:/temp.txt");
Employee e1 = new Employee("zhangsan", 22);
Employee e2 = new Employee("lisi", 20);
Employee e3 = new Employee("wangwu", 25);
t.writeEmployee(e1, 0);
t.writeEmployee(e3, 2);
System.out.println("第1个雇员的信息");
t.readEmployee(0);
System.out.println("第3个雇员的信息");
t.readEmployee(2);
System.out.println("第2个雇员的信息");
t.readEmployee(1);
}}您还可能感兴趣:java学习笔记系列:java学习笔记15--多线程编程基础2java学习笔记14--多线程编程基础1java学习笔记13--反射机制与动态代理java学习笔记12--异常处理java学习笔记11--集合总结java学习笔记10--泛型总结java学习笔记9--内部类总结java学习笔记8--接口总结java学习笔记7--抽象类与抽象方法java学习笔记6--类的继承、Object类java学习笔记5--类的方法java学习笔记4--对象的初始化与回收java学习笔记3--类与对象的基础java学习笔记2--数据类型、数组java学习笔记1--开发环境平台总结
优质网站模板}

我要回帖

更多关于 matlab读入dat文件 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信