您的位置:首页 > 编程语言 > Java开发

Java IO学习笔记

2008-12-24 13:50 495 查看
文件对象的生成和文件的创建

/*
* ProcessFileName.java
*
* Created on 2006年8月22日, 下午3:10
*
* 文件对象的生成和文件的创建
*/
package study.iostudy;
import java.io.*;
public class GenerateFile
{
public static void main(String[] args)
{
File dirObject = new File("d://mydir");
File fileObject1 = new File("oneFirst.txt");
File fileObject2 = new File("d://mydir", "firstFile.txt");
System.out.println(fileObject2);
try
{
dirObject.mkdir();
}catch(SecurityException e)
{
e.printStackTrace();
}
try
{
fileObject2.createNewFile();
fileObject1.createNewFile();
}catch(IOException e)
{
e.printStackTrace();
}
}
}

文件名的处理

/*
* ProcessFileName.java
*
* Created on 2006年8月22日, 下午3:29
*
* 文件名的处理
*/
package study.iostudy;
import java.io.*;
/*
* 文件名的处理
* String getName(); 获得文件的名称,不包含文件所在的路径。
* String getPath(); 获得文件的路径。
* String getAbsolutePath(); 获得文件的绝对路径。
* String getParent(); 获得文件的上一级目录的名称。
* String renameTo(File newName); 按参数中给定的完整路径更改当前的文件名。
* int compareTo(File pathName); 按照字典顺序比较两个文件对象的路径。
* boolean isAbsolute(); 测试文件对象的路径是不是绝对路径。
*/
public class ProcesserFileName
{
public static void main(String[] args)
{
File fileObject1 = new File("d://mydir//firstFile.txt");
File fileObject2 = new File("d://firstFile.txt");
boolean pathAbsolute = fileObject1.isAbsolute();
System.out.println("* * * * * * * * * * * * * * * * * * * * * * * * ");
System.out.println("There are some information of fileObject1's file name:");
System.out.println("fileObject1: " + fileObject1);
System.out.println("fileObject2: " + fileObject2);
System.out.println("file name: " + fileObject1.getName());
System.out.println("file path: " + fileObject1.getPath());
System.out.println("file absolute path: " + fileObject1.getAbsolutePath());
System.out.println("file's parent directory: " + fileObject1.getParent());
System.out.println("file's absoulte path: " + pathAbsolute);
int sameName = fileObject1.compareTo(fileObject2);
System.out.println("fileObject1 compare to fileObject2: " + sameName);
fileObject1.renameTo(fileObject2);
System.out.println("file's new name: " + fileObject1.getName());
}
}

测试和设置文件属性
/*
* SetterFileAttribute.java
*
* Created on 2006年8月22日, 下午3:51
*
* 测试和设置文件属性
*/
package study.iostudy;
import java.io.*;
public class SetterFileAttribute
{
/*
* File类中提供的有关文件属性测试方面的方法有以下几种:
* boolean exists(); 测试当前文件对象指示的文件是否存在。
* boolean isFile(); 测试当前文件对象是不是文件。
* boolean isDirectory(); 测试当前文件对象是不是目录。
* boolean canRead(); 测试当前文件对象是否可读。
* boolean canWrite(); 测试当前文件对象是否可写。
* boolean setReadOnly(); 将当前文件对象设置为只读。
* long length(); 获得当前文件对象的长度。
*/
public static void main(String[] args)
{
File dirObject = new File("d://mydir");
File fileObject = new File("d://mydir//firstFile.txt");
try
{
dirObject.mkdir();
fileObject.createNewFile();
}catch(IOException e)
{
e.printStackTrace();
}
System.out.println("* * * * * * * * * * * * * * * * * * * * * * * * ");
System.out.println("there are some information about property of file object:");
System.out.println("file object : " + fileObject);
System.out.println("file exist? " + fileObject.exists());
System.out.println("Is a file? " + fileObject.isFile());
System.out.println("Is a directory?" + fileObject.isDirectory());
System.out.println("Can read this file? " + fileObject.canRead());
System.out.println("Can write this fie? " + fileObject.canWrite());
long fileLen = fileObject.length();
System.out.println("file length: " +fileLen);
boolean fileRead = fileObject.setReadOnly();
System.out.println(fileRead);
System.out.println("Can read this file? " + fileObject.canRead());
System.out.println("Can write this fie? " + fileObject.canWrite());
System.out.println("* * * * * * * * * * * * * * * * * * * * * * * * ");
}
}

文件操作方法

/*
* FileOperation.java
*
* Created on 2006年8月22日, 下午4:25
*
* 文件操作方法
*/

package study.iostudy;
import java.io.*;
/*
* 有关文件操作方面的方法有如下几种:
* boolean createNewFile(); 根据当前的文件对象创建一个新的文件。
* boolean mkdir(); 根据当前的文件对象生成一目录,也就是指定路径下的文件夹。
* boolean mkdirs(); 也是根据当前的文件对象生成一个目录,
* 不同的地方在于该方法即使创建目录失败,
* 也会成功参数中指定的所有父目录。
* boolean delete(); 删除当前的文件。
* void deleteOnExit(); 当前Java虚拟机终止时删除当前的文件。
* String list(); 列出当前目录下的文件。
*/
public class FileOperation
{
public static void main(String[] args)
{
File fileObject = new File("d://mydir", "firstFile.txt");
File dirObject1 = new File("d://mydir//01");
File dirObject2 = new File("d://mydir//02");
File dirObject3 = new File("d://mydir");
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println("file object: " + fileObject);
System.out.println("dir object 1: " + dirObject1);
System.out.println("dir object 2" + dirObject2);
try
{
dirObject1.mkdir();
dirObject2.mkdirs();
}catch(SecurityException e)
{
e.printStackTrace();
}
try
{
fileObject.createNewFile();
}catch(IOException e)
{
e.printStackTrace();
}
String[] files = dirObject2.list();
for (int i = 0; i < files.length; i++)
{
System.out.println("list files in myhdir: " + files[i]);
}
System.out.println("dir object 1 exist? " + dirObject1.exists());
System.out.println("dir object 2 exist? " + dirObject2.exists());
boolean dir1Del = dirObject1.delete();
dirObject2.deleteOnExit();
System.out.println("dir object 1 exist? " + dirObject1.exists());
System.out.println("dir object 2 exist? " + dirObject2.exists());
}
}

找出一个目录下所有的文件
/*
* SearchFile.java
*
* Created on 2006年8月22日, 下午4:45
*
* 找出一个目录下所有的文件
*/
package study.iostudy;
import java.io.*;
public class SearchFile
{
public static void main(String[] args)
{
File dirObject = new File("D://aa");
Filter1 filterObj1 = new Filter1("HTML");
Filter2 filterObj2 = new Filter2("Applet");
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
System.out.println("list HTML files in directory: " + dirObject);
String[] filesObj1 = dirObject.list(filterObj1);
for (int i = 0; i < filesObj1.length; i++)
{
File fileObject = new File(dirObject, filesObj1[i]);
System.out.println(((fileObject.isFile())
? "HTML file: " : "sub directory: ") + fileObject);
}
System.out.println("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
String[] filesObj2 = dirObject.list(filterObj2);
for (int i = 0; i < filesObj2.length; i++)
{
File fileObject = new File(dirObject, filesObj2[i]);
System.out.println(((fileObject.isFile())
? "htm file: " : "sub directory: ") + fileObject);
}
}
}

class Filter1 implements FilenameFilter
{
String fileExtent;
Filter1(String extentObj)
{
fileExtent = extentObj;
}

public boolean accept(File dir, String name)
{
return name.endsWith("." + fileExtent);
}
}

class Filter2 implements FilenameFilter
{
String fileName;
Filter2(String fileName)
{
this.fileName = fileName;
}

public boolean accept(File dir, String name)
{
return name.startsWith(fileName + ".");
}
}

文件内容的拷贝(任意文件)
/*
* CopyFileContent.java
*
* Created on 2006年8月22日, 下午5:37
*
* 文件内容的拷贝(任意文件)
*/

package study.iostudy;
import java.io.*;
public class CopyFileContent
{
static void copyContent(FileInputStream inObj, FileOutputStream outObj)
{
int copyLen;
byte[] copyBuf = new byte[1024];
try
{
while ((copyLen = inObj.read(copyBuf, 0, 1024)) != -1)
{
String copyStr = new String(copyBuf);
System.out.println(copyStr);
outObj.write(copyBuf, 0, copyLen);
}
}catch(IOException e)
{
System.out.println("error: " + e);
}
}

public static void main(String[] args)
{
String secondFileName = "d://mydir//secondFile.wmv";
String thirdFileName = "d://mydir//thirdFile.wmv";
File fileObject = new File(thirdFileName);
FileInputStream inStream;
FileOutputStream outStream;
try
{
fileObject.createNewFile();
inStream = new FileInputStream(secondFileName);
outStream = new FileOutputStream(thirdFileName);
copyContent(inStream, outStream);
}catch(FileNotFoundException e)
{
e.printStackTrace();
}catch(IOException e)
{
e.printStackTrace();
}

}
}

文件随机访问
/*
* RandomFile.java
*
* Created on 2006年8月22日, 下午9:47
*
* 文件随机访问
*/
package study.iostudy;
import java.io.*;
/*
* 文件随机访问的方法
*
* void seek(long pos); 将文件指针移动到参数指定的位置。
* long getFilePointer(); 得到当前文件指针的位置。
* int skipBytes(int n); 将文件指针向前移动参数指定的n个字节。
* String readLine(); 从当前文件指定位置读取一行。
*
*/
public class RandomFile
{
public static void main(String[] args)
{
String tempStr;
int fileLines = 0;
long pointerLast = 0;
try
{
RandomAccessFile inObj = new RandomAccessFile("d://mydir//secondFile.txt", "rw");
while (inObj.readLine() != null)
fileLines++;
for (int i =0; i < fileLines / 2; i++)
{
inObj.seek(2 * i);
tempStr = inObj.readLine();
System.out.println(tempStr);
}
pointerLast = inObj.getFilePointer();
}catch(IOException e)
{
e.printStackTrace();
}
try
{
RandomAccessFile fileObj = new RandomAccessFile("d://mydir//secondFile.txt", "rw");
String writeStr = new String("Insert a string!");
fileObj.seek(pointerLast);
fileObj.writeChars(writeStr);
}catch(IOException e)
{
e.printStackTrace();
}
}
}

字符流处理
/*
* ProcesserCharacterStream.java
*
* Created on 2008年12月24日, 上午8:02
*
* 字符流处理
*
* java.io包中加入了专门用于字符流处理的类,这些类都是Reader和Writer类的子类,
* Reader和Writer是两个抽象类,只提供了一系列用于字符流处理的接口,不能生成这
* 两个类的实例。
* java.io包中用于字符流处理的最基本的类是InputStreamReader和OutputStreamWriter,
* 用来在字节流和字符流之间作为中介。
*
* 下面是InputStreamReader类和OutputStreamWriter类的常用方法:
*
* public InputStreamReader(InputStream in)
* 根据当前平台缺省的编码规范,基于字节流in生成一个输入字符流。
* public InputStreamReader(InputStream in, String sysCode)throws UnSupportedEncodingException
* 按照参数sysCode指定的编码规范,基于字节流in构造输入字符流,如果不支持参数sysCode中指定的编码规范,就会产生异常。
* public OutputStreamWriter(OutputStream out)
* 根据当前平台缺省的编码规范,基于字节流out生成一个输入字符流。
* public OutputStreamWriter(OutputStream out, String sysCode) throws UnsupportedEncodingException
* 按照参数sysCode指定的编码规范,基于字节流out构造输入字符流,如果不支持参数sysCode中指定的编码规范,就会产生异常。
* public String getEncoding()
* 获得当前字符流使用的编码方式。
* public void close() throws IOException
* 用于关闭流。
* public int read() throws IOException
* 用于读取一个字符。
* public int read(char[] cbuf, int off, int len)
* 用于读取len个字符到数组cbuf的索引off处。
* public void write(char[] cbuf, int off, int len) throws IOException
* 将字符数组cbuf中从索引off处开始的len个字符写入输出流。
* public void write(int c) throws IOException
* 将单个字符写入输入流。
* public void write(String str, int off, int len) throws IOException
* 将字符串str中从索引off位置开始的ltn个字符写入输出流。
*
* 此外,为了提高字符流处理的效率,在Java语言中,引入了BufferedReader和BufferWriter类,这两个类对字符流进行块处理。
* 两个类的常用方法如下:
* public BufferedReader(Reader in)
* 用于基于普通字符输入流in生成相应的缓冲流。
* public BufferedReader(Reader in, int bufSize)
* 用于基于普通字符输入流in生成相应的缓冲流,缓冲区大小为参数bufSize指定。
* public BufferedWriter(Writer out)
* 用于基于普通字符输入流out生成相应的缓冲流。
* public BufferedWriter(Writer out, int bufSize)
* 用于基于普通字符输入流out生在相应缓冲流,缓冲流大小为参数bufSize指定。
* public String readLine() throws IOException
* 用于从输入流中读取一行字符。
* public void newLine() throws IOException
* 用于向字符输入流中写入一行结束标记,值得注意的是,该标记不是简单的换行符"/n",而是系统定义的属性line.separator。
*/
package study.iostudy;
import java.io.*;
public class ProcesserCharacterStream
{
public static void main(String[] args)
throws FileNotFoundException, IOException
{
String lineStr;
FileInputStream fileInStream;
InputStreamReader inputReader;
BufferedReader bufReader;
FileOutputStream fileOutStream;
OutputStreamWriter outputWriter;
BufferedWriter bufWriter;
fileInStream = new FileInputStream("d://mydir//secondFile.txt");
inputReader = new InputStreamReader(fileInStream);
bufReader = new BufferedReader(inputReader);
System.out.println("------------------------------------------------");
System.out.println("There are file content before modify:");
while ((lineStr = bufReader.readLine()) != null)
System.out.println(lineStr);
bufReader.close();
inputReader.close();
fileInStream.close();
fileOutStream = new FileOutputStream("d://mydir//secondFile.txt");
outputWriter = new OutputStreamWriter(fileOutStream);
bufWriter = new BufferedWriter(outputWriter);
String newStr = new String("Modify the file ! /r/nThis is a nice thing. /r/nWe can write anything.");
bufWriter.write(newStr, 0, newStr.length());
System.out.println(newStr);
bufWriter.close();
outputWriter.close();
fileOutStream.close();
fileInStream = new FileInputStream("d://mydir//secondFile.txt");
inputReader = new InputStreamReader(fileInStream);
bufReader = new BufferedReader(inputReader);
System.out.println("------------------------------------------------");
System.out.println("There are file content after modify:");
while ((lineStr = bufReader.readLine()) != null)
System.out.println(lineStr);
bufReader.close();
inputReader.close();
fileInStream.close();
}
}

接收键盘输入数据
/*
* OutputKeyPress.java
*
* Created on 2006年8月23日, 上午9:27
*
* 接收键盘输入数据
*/
package study.iostudy;
import java.io.*;
public class OutputKeyPress
{
public static void main(String[] args)
{
System.out.println("This is a example about acceptance of keyboard.");
String tempStr = "0";
try
{
InputStreamReader inputReader;
BufferedReader bufReader;
inputReader = new InputStreamReader(System.in);
bufReader = new BufferedReader(inputReader);
tempStr = bufReader.readLine();
System.out.println("Input num is: " + tempStr);
}catch(IOException e)
{
e.printStackTrace();
}
int n = Integer.parseInt(tempStr);
int nultiNum = 1;
for (int i =1; i <= n; i++)
{
nultiNum *= i;
}
System.out.println("multiply of input number is: " + nultiNum);
}
}

过滤流
/*
* FilterStream.java
*
* Created on 2006年8月23日, 上午9:40
*
* 过滤流
*
* 过滤流在读/写数据的同时可以对数据进行处理,并提供了同步机制,
* 这样在同一时刻只有一个线程可以访问一个I/O流。在java.io包中,
* FilterInputStream和FilterOutputStream类是所有过滤输入流和
* 输出流的父类,它们是抽象类,本身不能生成任何实例,在这两上类
* 之下,分别实现了几物特殊的过滤输入流和输出流,利用这些特殊输
* 入流和输出流的实例可以进行流处理。
*
* 下面介绍几个过滤输入流和输出流的子类:
*
* BufferedInputStream 和 BufferedOutputStream
* 这两个类实现了带缓冲的过滤流,将任意的输入流和输出流绑定到缓
* 冲流上就会提高性能。
* 对于BufferedInputStream类,当系统读取数据时,数据按块读入缓
* 冲区,随后读操作直接访问缓冲区。使用BufferedOutputStream进行
* 输出时,数据首先写入缓冲区,当缓冲区满时,缓冲区中的数据写入
* 连接的输出流,BufferedOutputStream类提供的方法flush()可以强
* 制将缓冲区的内容全部写入输出流。
*
* DataInputStream 和 DataOutputStream
* 这两个类不仅能读写数据流,而且能读写各种各样的Java语言本身固
* 有的数据类型,如int、float等。
*
* PushbackInputStream
* PushbackInputStream类提供了方法将刚读过的字节退回到输入流中,
* 后面的内容就可以用到该字节。
*/

package study.iostudy;
import java.io.*;
public class FilterStream
{
public static void main(String[] args)
{
try
{
FileInputStream inStream;
FileOutputStream outStream;
BufferedInputStream bufInObj;
BufferedOutputStream bufOutObj;
DataInputStream dataInObj;
PushbackInputStream pushObj;
byte[] tempBuf = new byte[1024];
int copyLen;
inStream = new FileInputStream("d://mydir//secondFile.txt");
outStream = new FileOutputStream("d://mydir//thirdFile.txt");
bufInObj = new BufferedInputStream(inStream);
bufOutObj = new BufferedOutputStream(outStream);
dataInObj = new DataInputStream(inStream);
System.out.println(dataInObj.readBoolean());
while ((copyLen = bufInObj.read(tempBuf, 0, 1024)) != -1)
{
String copyStr = new String(tempBuf);
System.out.println(copyStr);
bufOutObj.write(tempBuf, 0, copyLen);
bufOutObj.flush();
}
int pushData;
byte[] pushByte = {'o', 'k'};
pushObj = new PushbackInputStream(
new FileInputStream("d://mydir//thirdFile.txt"), 1000);
while ((pushData = pushObj.read()) != -1)
{
if (Character.isLetter((char)pushData))
{
System.out.print((char)pushData);
}
else
{
System.out.println();
pushObj.unread(pushByte);
}
}
}catch(FileNotFoundException e)
{
System.out.println("File not found or persission denied.");
}catch(IOException e)
{
System.out.println("error:" + e);
}
}
/*
* 在上面的程序中,我们首先声明了FileInputStream类对象inStream和
* FileOutputStream类的对象outStream,接着声明了BufferInputStream
* 类对象bufObj、BufferedOutputStream类对象bufOutObj、
* DataInputStream类对象dataInObj以及PushbackInputStream类对象pushObj,
* 在try代码块中对上面这些对象进行初始化,程序的目的是通过BufferedInputStream
* 类对象bufInObj和BufferedOutputStream类对象bufOutObj将secondFile.txt
* 文件中内容输出到屏幕,并将该文件的内容写入thirdFile.txt文件中,值得注意的是,
* 将secondFile.txt文件中的内容输出之前,程序中使用
* "System.out.println(dataInObj.readBoolean());" 语句根据readBoolean()结果
* 输出了true,而secondFile.txt文件开始内容为“Modify”,和一个字符为M,
* 因此输出的文件内容没有“M”字符,thirdFile.txt文件中也比secondFile.txt
* 文件少第一个字符“M”。随后,通过PushbackInputStream类对象pushObj读取
* thirdFile.txt文件中的内容,输出读到的字符,当读到的不是字符,输出回车,将字符
* 数组pushByte写回到thirdFile.txt文件中,也就是“ok”写回文件中。
*/

}

字节流
一、InputStream的API

1、public int read()

从输入流读取下一个数据字节。返回 0 到 255 范围内的 int 字节值。如果因已到达流末尾而没有可用的字节,则返回值 -1。

2、public int read(byte[] b)

从输入流中读取一定数量的字节并将其存储在缓冲区数组 b 中。以整数形式返回实际读取的字节数。如果因为流位于文件末尾而没有可用的字节,则返回值 -1;否则,至少可以读取一个字节并将其存储在 b 中。此方法等同于read(b, 0, b.length)

3、public int read(byte[] b, int off, int len)
将输入流中最多 len 个数据字节读入字节数组。尝试读取多达 len 字节,但可能读取较少数量。以整数形式返回实际读取的字节数。如果由于已到达流末尾而不再有数据,则返回 -1。
参数:
b - 读入数据的缓冲区。
off - 在其处写入数据的数组 b 的初始偏移量。
len - 要读取的最大字节数。

[b]二、OutputStream的API[/b]

1、public void write(int b)

将指定的字节写入此输出流。write 的常规协定是:向输出流写入一个字节。要写入的字节是参数 b 的八个低位。b 的 24 个高位将被忽略。

2、public void write(byte[] b)

将 b.length 个字节从指定的字节数组写入此输出流。write(b) 的常规协定是:应该与调用 write(b, 0, b.length) 的效果完全相同。

3、public void write(byte[] b, int off, int len)
将指定字节数组中从偏移量 off 开始的 len 个字节写入此输出流。write(b, off, len) 的常规协定是:将数组 b
中的某些字节按顺序写入输出流;元素 b[off] 是此操作写入的第一个字节,b[off+len-1] 是此操作写入的最后一个字节。
参数:
b - 数据。
off - 数据中的初始偏移量。
len - 要写入的字节数。

4、public void flush()
刷新此输出流并强制写出所有缓冲的输出字节。flush 的常规协定是:如果此输出流的实现已经缓冲了以前写入的任何字节,则调用此方法指示应将这些字节立即写入它们预期的目标。
public class TestIOStream {
public static void main(String[] args) {
testStream();
testBufferedStream();
testSelectStream();
}

/**
* 字节流测试
*/
public static void testStream() {
InputStream fis = null;
OutputStream fos = null;
try {
fis = new FileInputStream("C://x.txt");
fos = new FileOutputStream("C://xcopy.txt");
long num = 0; //读取字节计数
int bt = 0; //每次读入字节内容
//当读入文件末尾时,读入数据的值为-1
//每次读入一个字节,存放到变量bt中,直到读完整个文件
while ((bt = fis.read()) != -1) {
// System.out.print(bt); //以数字的形式逐个输出文件的每个字节
System.out.print((char) bt); //以字母的形式逐个输出文件的每个字节
fos.write(bt); //将字节写入输出流中,实现文件的copy功能
num++;
}
System.out.println("读取的字节数为" + num);
fis.close();
fos.close();
} catch (FileNotFoundException e) {
System.out.println("找不到指定的文件!");
e.printStackTrace();
} catch (IOException e) {
System.out.println("文件读取时发生IO异常!");
e.printStackTrace();
}
}

/**
* 缓冲的字节流测试
*/
public static void testBufferedStream() {
int buffer = 10; //缓冲大小
try {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("C://x.txt"));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("C://bf2.txt"));
int bench = 0;
byte bts[] = new byte[buffer]; //创建字节流缓存
while ((bis.read(bts)) != -1) {
bos.write(bts); //将字节写入输出流中,实现文件的copy功能
bench++;
}
System.out.println("bench=" + bench);
//将输入流缓冲区中的数据全部写出(千万记住)
bos.flush();
bis.close();
bos.close();
} catch (FileNotFoundException e) {
System.out.println("找不到指定的文件!");
e.printStackTrace();
} catch (IOException e) {
System.out.println("文件读取时发生IO异常!");
e.printStackTrace();
}
}

/**
* 字节流的选择读取测试
*/
public static void testSelectStream() {
OutputStream fos = null;
int buffer = 25;
try {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("C://x.txt"));
fos = new FileOutputStream("C://testSelectStream.txt");

byte bts[] = new byte[buffer]; //创建缓存
//从输入流的第5个字节开始,往后读取10个字节,存放到缓存bts中
//这个方法有个陷阱,缓存buffer的大小最小为“偏移量+要读取字节数”,在次最小应该为15,否则抛IndexOutOfBoundsException异常
bis.read(bts, 5, 10);
//将字节写入输出流中,实现文件的copy功能
fos.write(bts);

bis.close();
fos.close();
} catch (FileNotFoundException e) {
System.out.println("找不到指定的文件!");
e.printStackTrace();
} catch (IOException e) {
System.out.println("文件读取时发生IO异常!");
e.printStackTrace();
}
}
}

顺序输入流
/*
* SequenceStream.java
*
* Created on 2008年12月23日, 上午10:55
*
* 顺序输入流
*
* java.io包中提供了SequenceInputStream类,用于将多个输入流顺序连接起来,
* 使它们看起来就像一个较长的流。
*/
package study.iostudy;
import java.io.*;
public class SequenceStream
{
public static void main(String[] args)
{
FileInputStream fileStream1, fileStream2;
try
{
String allStr;
fileStream1 = new FileInputStream("d://mydir//secondFile.txt");
fileStream2 = new FileInputStream("d://mydir//thirdFile.txt");
SequenceInputStream seqStream = new SequenceInputStream(fileStream1, fileStream2);
BufferedInputStream bufObj = new BufferedInputStream(seqStream);
byte[] bufByte = new byte[1024];
while (bufObj.read(bufByte, 0, 1024) != -1)
{
String tempStr = new String(bufByte);
System.out.println(tempStr);
}
}catch(FileNotFoundException e)
{
System.out.println("File not found or no permission.");
}catch(IOException e)
{
System.out.println("error:" + e);
}
}
}

对象串行化

/*
* SerializableObject.java
*
* Created on 2008年12月23日, 上午11:26
*
* 对象串行化
*   对象通过写出描述自己状态的数值来记录自己,这个过程叫做对象串行化。对象的寿命通
* 常是随着生成该对象的程序的终止而终止,在有些情况下,需要将对象的状态保存下来,然后
* 在必要的时候将对象恢复,值得注意的是,如果变量是另一个对象的引用,则引用的对象也要
* 串行化,串行化是一个递归的过程,可能会涉及到一个复杂树结构的串行化,比如包括原有对
* 象,对象的对象等。
*   在java.io包中,接口Serializable是实现对象串行化的工具,只有实现了Serializable
* 的对象才可以被串行化。Serializable接口中没有任何的方法,当一个类声明实现Seriali-
* zable接口时,只是表明该类遵循串行化协议,而不需要实现任何特殊的方法。
*   在进行对象串行化时,需要注意将串行化的对象和输入、输出流联系起来,首先通过对
* 象输出流将对象状态保存下来,然后通过对象输入流将对象状态恢复。
*/

package study.iostudy;

import java.io.*;

class Book implements Serializable
{
String isbn;
String name;
int page;
String type;
public Book(String isbn, String name, int page, String type)
{
this.isbn = isbn;
this.name = name;
this.page = page;
this.type = type;
}
}

public class SerializableObject implements Serializable
{
public static void main(String[] args)
throws IOException, ClassNotFoundException
{
Book bookObj = new Book("7-02-016450-1", "Java", 218, "programming");
FileOutputStream fileOStream = new FileOutputStream("temp.ser");
ObjectOutputStream objOutStream = new ObjectOutputStream(fileOStream);
try
{
objOutStream.writeObject(bookObj);
objOutStream.close();
}catch(IOException e)
{
e.printStackTrace();
}
bookObj = null;
FileInputStream fileInStream = new FileInputStream("temp.ser");
ObjectInputStream objInStream = new ObjectInputStream(fileInStream);
try
{
bookObj = (Book)objInStream.readObject();
objInStream.close();
}catch(IOException e)
{
e.printStackTrace();
}
System.out.println("------------------------------------------------");
System.out.println("There are information about book:");
System.out.println("ISBN Number: " + bookObj.isbn);
System.out.println("Book Name: " + bookObj.name);
System.out.println("Book Page: " + bookObj.page);
System.out.println("Book Type: " + bookObj.type);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: