您的位置:首页 > 其它

IO数据流总结(7)

2015-10-27 19:31 281 查看
IO流体系:

字符流:

Reader
Writer

|--BufferedReader: |--BufferedWriter

|--LineNumberReader |--CharArrayWriter

|--CharArrayReader |--StringWriter

|--StringReader |--OutputStreamWriter

|--InputStreamReaer |--FileWriter

|--FileReader |--PrintWriter

字节流:

InputStream OutputStream

|--FileInputStream: |--FileOutputStream

|--FilterInputStream |--FilterOutputStream

|--BufferedInputStream |--BufferedOutputStream

|--DataInputStream |--DataOutputStream

|--ByteArrayInputStream |--ByteArrayOutputStream

|--ObjectInputStream |--ObjectOutputStream

|--SequenceInputStream |--PipedOutputStream

|--PipedInputStream |--PrintStream

文件File类

java.lang.Object

|--java.io.File

|--java.io.RandomAccessFile 此类的实例支持对随机访问文件的读取和写入。

|--java.security.Permission

|--java.io.FilePermission 此类表示对文件和目录的访问。FilePermission 由路径名和对该路径名有效的操作集合组成。

字节流的两个顶层父类:抽象类

1,InputStream 2,OutputStream.

字符流的两个顶层父类:抽象类

1,Reader 2,Writer

FileReader 用于读取字符流。输出文本文件。

1.构造方法
FileReader fr = new FileReader("demo.txt")读Demo文件

2.常用方法

读取
read(); 取一个字符

read(char[] cbuf,
int off, int len)将字符读入数组某一部分

reset()
; 重置该流。

刷新 fr.flush();

关闭 fr.close();

3.实例:

FileReader fr= new FileReader("D:\\test01.txt");

char[] ch = new char[10]
;

int len =
0 ;

while((len = fr.read(ch))
!= -1){

System.out.println(new String(ch,0,len));

}

fr.close();

FileWriter

1.构造方法:FileWriter fw = new FileWriter("demo.txt“)覆盖Demo文件

FileWriter
fw = new FileWriter("demo.txt",ture) 像Demo文件继续写入

2.常用方法

添加 append();=write(char[] /int/String)
向字符流中添加信息

刷新 fw.flush();

关闭 fw.close();

3.实例

FileWriter fw = new FileWriter("D:\\test02.txt",true);

fw.write("xixi");

fw.flush();

fw.close();

IOException

1.产生

文件路径不正确 捕捉并处理

保证流资源关闭放入finnaly{}

2实例:

FileWriter fw = null ;

try {

fw = new FileWriter("D:\\test012.txt", true);

fw.write("xixi");

fw.flush();

} catch (IOException e)
{

// TODO 自动生成的
catch 块

e.printStackTrace();

} finally {

if (fw != null)

try {

fw.close();

} catch (IOException e)
{

// TODO 自动生成的
catch 块

e.printStackTrace();

}

}

BufferedReader 读入缓冲区,提高效率

1.构造函数

BufferedReader(Reader in,
int sz) 传入一个Reader对象,大小可选设置和默认。

2.常用方法

int = read();
读取一个字符

int
= read(char[] cbuf, int off,
int len) ; 读取数组一部分

String
= readLine() ;
读取一行

3.实例:使用一行读取数据

BufferedReader br = new BufferedReader(new FileReader("D:\\test01.txt"));

读取一行输出

String s ;

while(( s = br.readLine())!=null)

System.out.println(s);

BufferedWriter 输出缓冲区,提高效率

1.构造函数

BufferedWriter(Writer out,
int sz) 传入一个Writer对象,大小可选设置和默认。

2.常用方法

write(int c/(char[] cbuf,
int off, int len/String,int off, int len ) 写入一个字符、一个数组、一个字符串

newLine()
;插入一个回车符

3.实例

BufferedWriter bw = new BufferedWriter(new FileWriter("D:\\test03.txt"));

bw.write("ssjaskdfcljdsafjkjasnfkdsjakd");

bw.newLine();

bw.append("874377384");

bw.flush();

bw.close();

MyBufferedReader

自己编写一个缓存输入流

public class MyBufferedReader extends Reader
{

private Reader r; //
私有维护流

private char[] buff = new char[1024];//
缓存区

private int pos =
0; // 纪录读取数据指针

private int count =
0; // buff里都进来的指针

// 构造函数,接受Reader对象

MyBufferedReader(Reader reader)
{

this.r = reader;

}

// 一次都一个

public int MyRead() throws IOException
{

if (count ==
0) {

count = r.read(buff);

pos =
0;

}

if (count ==
-1)

return -1;

char ch = buff[pos++];

count--;

return ch;

}

//一次一行

public String MyReadLine() throws IOException
{

StringBuilder sb = new StringBuilder();

int ch =
0;

while ((ch = r.read())
!= -1) {

if (ch == '\r')

continue;

if (ch == '\n')

return sb.toString();

sb.append((char) ch);

}

if (sb.length()
!= 0)

return sb.toString();

return null;

}

//关闭

public void MyClose() throws IOException
{

r.close();

}

}

LineNumberReader读取的文件可以添加行号,有助于查看。

1.实例:读取Test01.txt里的全部内容,标上行号,这和行号通过setLineNumber(7)设置,这表示文件第一行内容行号为8,一次类推。

FileReader fr = new FileReader("D:\\test01.txt");

LineNumberReader lnr = new LineNumberReader(fr);

String line = null;

lnr.setLineNumber(7);

while((line=lnr.readLine())!=null){

System.out.println(lnr.getLineNumber()+":"+line);

}

lnr.close();

FileInputStream 用于读取诸如图像数据之类的原始字节流。

1.构造方法

FileInputStream(File )
添加file对象

FileInputStream(String )
添加路径文件

2.方法

int
= read() ;读一个字节

int
= read(byte[] b) 读一个字节数组

3.实例

// 第三种,使用获得文件长度创建数组大小,一次性来读取数据 不建议:因为文件如果太大,一次性读取会很慢

public static void FileInputStreamLen() throws IOException
{

FileInputStream fis = new FileInputStream("D:\\test02.txt");

int i = fis.available();

byte[] bytes = new byte[i];

fis.read(bytes);

System.out.println(new String(bytes));

}

// 第二种,使用字节数组Buty[]读取
建议使用此方法

public static void FileInputStreamBytes() throws IOException
{

FileInputStream fis = new FileInputStream("D:\\test02.txt");

byte[] bytes = new byte[1024];

int len =
0;

while ((len = fis.read(bytes))
!= -1) {

System.out.println(new String(bytes));

}

}

// 第一种单字节读取 不建议使用此方法,效率低

public static void FileInputStreamByte() throws IOException
{

FileInputStream fis = new FileInputStream("D:\\test02.txt");

int ch =
0;

while ((ch = fis.read())
!= -1) {

System.out.println((char) ch);

}

}

FileOutputStream 用于写入诸如图像数据之类的原始字节的流。

1.构造方法

FileOutputStream(File file)
传入file对象

FileOutputStream(File file,
boolean append) 传入file对象,是否相依有文件夹续写

FileOutputStream(String name)
传入路径

FileOutputStream(String name,
boolean append) 传入路径,是否相依有文件夹续写

2.方法:

void = write(byte[] b)
参数可以使 byte 、byte[]、bute[],from,end

3.实例

private static void fileOutputStream01() throws IOException
{

// 不管文件是否存在,覆盖并写入以下字节

FileOutputStream fos = new FileOutputStream("D:\\test11.txt");

fos.write('o');

fos.flush();

fos.write('s');

fos.close();

}

public static void fileOutputStream02() throws FileNotFoundException,
IOException {

// 如果该文件存在,则在文件中添加字节;如果文件不存在,创建文件并写入字节。

FileOutputStream fos = new FileOutputStream("D:\\test10.txt", true);

fos.write('o');

fos.flush();

fos.close();

}

System.in 标准输入流键盘使用练习

public static void print_chars() throws IOException
{

//读取字符数组,当一次性大于数组时会分多次输出

InputStream is =
System.in;

byte[] bytes = new byte[10];

int len =
0 ;

while((len = is.read(bytes))!=
-1){

System.out.println(new String(bytes,0,len));

}

}

public static void print_char() throws IOException
{

// 读取一个字符,使用键盘接收字符,打印到控制台上

InputStream is =
System.in;

int ch = is.read();

System.out.println((char) ch);

}

InputStreamReader 是字节输入流通向字符输入流的桥梁
可以通过指定编码表进行转换。

1.构造方法

InputStreamReader(InputStream in)
传入一个字节输入流,用默认码表转变为字符输入流

InputStreamReader(InputStream in,
String name) 传入一个字节输入流,用例如name(utf-8)指定码表转变为字符输入流

2.常用方法

String = getEncoding(); 返回此流使用的字符编码的名称。

int = read()
;读一个字节

3.实例:

public static void InputStreamReader02() throws IOException
{

// 加上缓冲区,使用每次都去一行输出文件内容

BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("D:\\test02.txt")));

String s = null;

while ((s = br.readLine())
!= null) {

System.out.println(s);

}

}

public static void InputStreamReader01() throws IOException
{

// 将字节输入流变为字符输入流,并打印

InputStreamReader isr = new InputStreamReader(new FileInputStream("D:\\test01.txt"));

int ch =
0;

while ((ch = isr.read())
!= -1) {

System.out.println((char) ch);

}

}

OutputStreamWriter 是字符输出流通向字节输入流的桥梁

1.构造方法

OutputStreamWriter(OutputStream out,String
name) 参数为字节输出流对象,可以添加编码表

2.常用方法

String = getEncoding(); 返回此流使用的字符编码的名称。

write(int c)
(char[] cbuf, int off, int len) (String str,
int off, int len) 参数字符、数组一部分、字符串一部分

3.实例

public static void OutputStreamWriter01() throws IOException
{

// 将中文输入到文件中

OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("D:\\test13.txt"));

osw.write("哈哈");

osw.close();

}

File

1.构造方法

File(String pathname)
直接将路径名封装 "D:\\test.txt"

File(File parent, String child)

File(String parent, String child)

File(URI uri)

2.常用字段

static String = pathSeparator
与系统有关的路径分隔符,为了方便,它被表示为一个字符串。

static char
= pathSeparatorChar
与系统有关的路径分隔符。

static String = separator
与系统有关的默认名称分隔符,为了方便,它被表示为一个字符串。

static char = separatorChar
与系统有关的默认名称分隔符。

3.重点方法
//返回该file对象目录的所有文件名,可添加过滤器

//返回一个字符串数组,这些字符串指定此抽象路径名表示的目录中的文件和目录。

String[] s1 = file2.list();

for(String s : s1)

System.out.println(s);

//listFiles()返回一个抽象路径名数组,这些路径名表示此抽象路径名表示的目录中的文件。

File[] files = file2.listFiles();

for(File file : files){

System.out.println(file.getName());

}

FilenameFilter过滤器:通过实现FilenameFilter接口添加条件使用

实例:(过滤器列出符合的文件)

//FilenameFilter的实现类代码,创建一个类实现该接口

class FilenameFilterByTest implements FilenameFilter{

public boolean accept(File arg0,
String name) {

//返回的name是筛选条件,其中字符串的末尾设置为“。txt”的可以返回True,其他的全部返回false

return name.endsWith(".txt");

}

}

//使用过滤器获取该目录下所有文件名和目录的代码

//返回一个字符串数组,这些字符串指定此抽象路径名表示的目录中的文件和目录。

String[] s1 = file3.list(new FilenameFilterByTest());

for(String s : s1)

System.out.println(s);

实例2(深度遍历)

//
深度遍历的方法,采用递归方式

public static void catAllFile(File files, int level)
{

//
深度遍历方法

System.out.println(get(level)
+ files.getAbsolutePath());

level++;

File[] file = files.listFiles();

for (File f : file)
{

if (f.isDirectory())
{

catAllFile(f, level);

} else {

System.out.println(get(level)
+ f.getAbsolutePath());

}

}

}

//
文件层次缩进的设置

private static String
get(int level)
{

StringBuffer sb = new StringBuffer();

for (int i =
0; i < level; i++)

sb.append(" ");

sb.append("|--");

return sb.toString();

}

实例3
//File[] file = File.listRoots() 列出可用的文件系统根。

File[] fileroots =
File.listRoots();

for(File fileroot : fileroots){

System.out.println(fileroot.getName());

}

3.常用方法

获取

String l1 = file1.getName();
//获取文件名

String l2 = file1.getPath();
//获取文件路径和文件名

String l3 = file1.getParent();
//只获取路径

File l2 = file1.getParentFile();
//上一级目录路径,没有上级目录返回空,

File l3 = file3.getParentFile();
//返回空 例子:File file3 = new File("D:\\");

long l1 = file1.lastModified();
//返回文件最后一次被修改的时间(毫秒值)。文件不存在返回0.

long l2 = file1.length();
//返回由此抽象路径名表示的文件的长度。

long l1 = file2.getFreeSpace();//返回此抽象路径名指定的分区中未分配的字节数。

long l2 = file2.getTotalSpace();//返回此抽象路径名指定的分区大小。

long l3 = file2.getUsableSpace();//返回此抽象路径名指定的分区上可用于此虚拟机的字节数。

String s = file2.getCanonicalPath()
;// 返回此抽象路径名的规范形式。

File f = file1.getCanonicalFile()
;// 返回此抽象路径名的规范形式。

String s = file2.getAbsolutePath();//
返回此抽象路径名的绝对路径名形式。

File f = file1.getAbsoluteFile()
;// 返回此抽象路径名的绝对路径名形式。

新建和删除

boolean b = file1.renameTo(file2);
重新命名此抽象路径名表示的文件。

boolean l3 = file3.createNewFile();
////当且仅当只存在路径不存在文件时,创建该文件。

File f =
File.createTempFile("20151003", ".txt");//在默认临时文件目录中创建一个空文件,使用给定前缀和后缀生成其名称。创建文件C:\Users\Admin\AppData\Local\Temp\201510034767322862535394102.txt

File f =
File.createTempFile("20151003", ".txt",file3);//在默认临时文件目录中创建一个空文件,使用给定前缀和后缀生成其名称。创建文件D:\test1\test2\201510035127300883661714610.txt

boolean l1 = file3.mkdirs();
//创建指定的目录,包括所有必需但不存在的父目录(不包括文件)。

boolean l2 = file2.mkdir();
//创建此抽象路径名指定的目录。(不能创建文件)

boolean l1 = file3.delete();
//如果该目录下只有该文件可以删除该文件,不可以删除上级文件。

file2.deleteOnExit();
//在虚拟机终止时,请求删除此抽象路径名表示的文件或目录。无返回值

测试和判断

boolean l2 = file3.isAbsolute();
//测试是否为绝对路径

boolean l3 = file3.isFile();
//是否是一个File对象

boolean l4 = file3.isDirectory();
//是否是一个文件夹

boolean l5 = file3.isHidden();
//是否是个隐藏文件

boolean
l1 = file3.exists();
//测试此抽象路径名表示的文件或目录是否存在。

Properties *Properties
类表示了一个持久的属性集。

*Properties 可保存在流中或从流中加载。

*属性列表中每个键及其对应值都是一个字符串。通常存取配置文件。

1.构造方法

2.常用方法

getProperty(String key)
:String 用指定的键在此属性列表中搜索属性。

getProperty(String key, String defaultValue)
:String 用指定的键在属性列表中搜索属性。

setProperty(String key, String value)
如果没有key则添加键值对;如果有key值,则修改Value值。调用 Hashtable 的方法 put。

stringPropertyNames()
: Set<String>返回此属性列表中的键集,其中该键及其对应值是字符串,如果在主属性列表中未找到同名的键,则还包括默认属性列表中不同的键。

3.与IO流结合的方法

list(PrintStream out) 将属性列表输出到指定的输出流System.out。直接将map集合Properties的数据打印到控制台

list(PrintWriter out)
将属性列表输出到指定的输出流System.in。直接将键盘输入流获取的数据存到之和Properties中。

//将集合中的数据保存到硬盘上---数据持久化

store(OutputStream out, String comments)
comments这个字符串是描述添加数据的信息的内容,可添加可不写!

store(Writer writer, String comments)
comments这个字符串是描述添加数据的信息的内容,可添加可不写!

//将银盘文件上的数据读取到集合上

load(InputStream inStream)


load(Reader reader)

实例1:将已经存在硬盘上的配置文件中的某个信息修改掉

//1.获取配置文件,加载到内存集合中

//2.map集合方法通过键修改值数据

//3。将修改之后的数据硬盘持久化

File file = new File("D:\\test\\test.txt");

InputStream fis = new FileInputStream(file);

Properties p = new Properties();

p.load(fis);

p.setProperty("age", "11");

OutputStream fos = new FileOutputStream(file);

p.store(fos, "xiugaizhihou");

p.list(System.out);

实例2:

//实例:纪录一个软件的试用次数,运行超过5次则提示“你已使用5次,请购买正版!”并关闭该软件。

//思路:运行一次计数一次,所以关闭程序计数数据不能丢失,所以需要Properties<time,value>类通过io流银盘持久化数据。

private static void getCount() throws IOException
{

File file = new File("info.Properties"); //
定义一个File文件目录

if (!file.exists()) //
判断file标识的文件路径是否存在

file.createNewFile(); //
不存在就创建

InputStream fis = new FileInputStream(file); //
该文件关联字节输入流

Properties prop = new Properties(); //
创建Properties集合

prop.load(fis); //
将输入流加载到内存,关联Properties集合

String value = prop.getProperty("Time"); //
查看count对应的数值,做判断

int count =
0;

if (value != null) //
判断

count =
Integer.parseInt(value); //
如果有值,则将字符串变为int类型

if (count >=
5) // 如果次数大于等于5,则停止

throw new Error("你已使用5次,请购买正版!");

count++; //
如果次数小于5,则计数+1

prop.setProperty("Time", count + ""); //
修改集合中的数据

OutputStream fos = new FileOutputStream(file); //
创建输出流关联

prop.store(fos, "info"); //
将集合输出到硬盘

fos.close();

fis.close();

}

实例:综合练习:将一个目录里边的所有扩展名.java文件的绝对路径保存在一个文件里,方便查看。

public class filename_list
{

public static void main(String[] args) throws IOException
{

// 指定一个文件夹

File file = new File("test");

MyFilenameFilter mf = new MyFilenameFilter();

ArrayList<File> arr = new ArrayList<File>();

// huoqusuoyou

getFilename(file, mf, arr);

// FileWriter fw =
new FileWriter(file,"javalist.txt");

setFilename(file, arr);

}

private static void setFilename(File file,
ArrayList<File> arr) throws IOException
{

// TODO 自动生成的方法存根

FileWriter fw = new FileWriter(new File(file, "javalist.txt"));

for (File s : arr)
{

fw.write(s.getAbsolutePath());

fw.write("\r\n");

fw.flush();

}

fw.close();

}

private static void getFilename(File file,
MyFilenameFilter mf, ArrayList<File> arr)
{

File[] files = file.listFiles();

for (File f : files)
{

if (f.isDirectory())

getFilename(f, mf, arr);

// String s = f.getAbsolutePath();

else {

if (mf.accept(file, f.getName()))

arr.add(f);

}

}

}

}

class MyFilenameFilter implements FilenameFilter
{

@Override

public boolean accept(File file,
String name) {

// TODO 自动生成的方法存根

return name.endsWith(".java");

}

}

PrintStream 打印流
为其他输出流添加了功能,使它们能够方便地打印各种数据值表示形式。直接原样输出。

1.构造方法

PrintStream(File
file) 创建具有指定文件且不带自动行刷新的新打印流。

PrintStream(File
file, String csn) 创建具有指定文件名称和字符集且不带自动行刷新的新打印流。

PrintStream(OutputStream
out) 创建新的打印流。

PrintStream(OutputStream
out, boolean autoFlush) 创建新的打印流。

PrintStream(OutputStream
out, boolean autoFlush, String encoding) 创建新的打印流。

PrintStream(String
fileName) 创建具有指定文件名称且不带自动行刷新的新打印流。

PrintStream(String
fileName, String csn) 创建具有指定文件名称和字符集且不带自动行刷新的新打印流。

2.常用方法

ps.write(609);
将int = 609 转成二进制,取最低8位存进去。

ps.print(609);
原样输出 ,先变成字符串在输出

PrintWriter 打印流
向文本输出流打印对象的格式化表示形式。此类实现在 PrintStream 中的所有
print 方法。

1.构造方法

PrintWriter(File
file) 使用指定文件创建不具有自动行刷新的新 PrintWriter。

PrintWriter(File
file, String csn) 创建具有指定文件和字符集且不带自动刷行新的新 PrintWriter。

PrintWriter(OutputStream
out) 根据现有的 OutputStream 创建不带自动行刷新的新 PrintWriter。

PrintWriter(OutputStream
out, boolean autoFlush) 通过现有的 OutputStream 创建新的 PrintWriter。

PrintWriter(String
fileName) 创建具有指定文件名称且不带自动行刷新的新 PrintWriter。

PrintWriter(String
fileName, String csn) 创建具有指定文件名称和字符集且不带自动行刷新的新 PrintWriter。

PrintWriter(Writer
out) 创建不带自动行刷新的新 PrintWriter。

PrintWriter(Writer
out, boolean autoFlush) 创建新 PrintWriter。

SequenceInputStream 序列流 表示其他输入流的逻辑串联。

1.构造方法

SequenceInputStream(Enumeration<?
extends InputStream> e)使用枚举,多个添加

SequenceInputStream(InputStream s1, InputStream s2)
2个添加

2.常用方法

available()
: int 返回不受阻塞地从当前底层输入流读取(或跳过)的字节数的估计值,方法是通过下一次调用当前底层输入流的方法。

3.枚举函数使用方法

//利用迭代器设计枚举对象

//1.创建集合,加入三个输入流

ArrayList<FileInputStream> arr = new ArrayList<FileInputStream>();

arr.add(fis1);

arr.add(fis2);

arr.add(fis3);

//3.实现枚举的内部方法,因为和迭代器功能重复,所以可以调用迭代器的方法

Iterator<FileInputStream> it =arr.iterator();

//2.自己创建枚举对象,采用匿名类方式创建

Enumeration<FileInputStream> e1 = new Enumeration<FileInputStream>(){

@Override

public boolean hasMoreElements()
{

// TODO 自动生成的方法存根

return it.hasNext();

}

@Override

public FileInputStream
nextElement() {

// TODO 自动生成的方法存根

return it.next();

}

};

4.分割文件和合并文件

/*

* 完成一个文件的分割和合成。D:\demo\0.wmv,分解成15m的文件+配置文件。合成源文件D:\demo\0.wmv

*/

public class Demo
{

// 需要分割文件和文件分割大小设定

private static final int SIZE =
1024 * 1024 * 15;

public static void main(String[] args) throws IOException
{

//
//分割函数,带参数文件地址 (分割division文件file)

//
File file = new File("D:\\Demo\\0.wmv");

// divisionfile(file);

//
合成函数,带参数文件目录 (合并fuse文件file)

File dir = new File("D:\\Demo");

fusefile(dir);

}

// 合并文件的函数

public static void fusefile(File dir) throws IOException
{

//
查看文件家是否存在

if (!dir.exists())

throw new FileNotFoundRuntimeException("文件或路径不存在,请确认!");

//
存在则获取配置文件的信息

File[] files = dir.listFiles(new suffixFilter(".Properties"));

if (files.length !=
1)

throw new FileNotFoundRuntimeException("当前目录下存在0个或多个Properties信息文件,请确认!");

//
将配置文件信息传给fileinfo

File fileinfo = files[0];

//
输入流关联文件提取信息

FileInputStream fis = new FileInputStream(fileinfo.getAbsolutePath());

Properties prop = new Properties();

prop.load(fis);

//
将文件碎片放进数组

files = dir.listFiles(new suffixFilter(".part"));

if ((Integer.parseInt(prop.getProperty("partnumber"))
- 1) != files.length)

throw new FileNotFoundRuntimeException(

"您的文件碎片个数不正确,应该是" + (Integer.parseInt(prop.getProperty("partnumber"))
- 1) + "个,请确认!");

//
创建一个序列流,添加所有碎片

ArrayList<FileInputStream> arr = new ArrayList<FileInputStream>();

for (int i =
0; i < files.length; i++)
{

arr.add(new FileInputStream(files[i].getAbsoluteFile()));

}

//
枚举对象

Enumeration<FileInputStream> e =
Collections.enumeration(arr);

//
创建序列化流

SequenceInputStream sis = new SequenceInputStream(e);

//
创建新合成文件的输出流

FileOutputStream fos = new FileOutputStream(new File(dir, prop.getProperty("FileName")));

byte[] bytes = new byte[SIZE];

int len =
0;

while ((len = sis.read(bytes))
!= -1)

fos.write(bytes,
0, len);

fos.close();

}

// 分割文件的函数

public static void divisionfile(File file) throws IOException
{

//
查看文件或目录是否存在

if (!file.exists())

//
不存在,则抛出异常停止运行,船建一个异常类

throw new FileNotFoundRuntimeException("文件或路径不存在,请确认后在分割!");

//
文件存在,创建缓存数组大小=分割单个文件大小

byte[] bytes = new byte[SIZE];

//
输入流关联源文件

FileInputStream fis = new FileInputStream(file);

//
创建输出文件流

FileOutputStream fos = null;

int len =
0;

int count =
1;

//
分割并保存

while ((len = fis.read(bytes))
!= -1) {

fos = new FileOutputStream(new File(file.getParentFile().toString(),
(count++) + ".part"));

fos.write(bytes,
0, len);

fos.close();

}

//
创建文件分割信息,将文件信息存储在集合中

Properties prop = new Properties();

prop.setProperty("FileName", file.getName());

prop.setProperty("partnumber", count + "");

//
关联配置文件信息输出流文件关联

fos = new FileOutputStream(new File(file.getParentFile().toString(),
(count) + ".Properties"));

prop.store(fos, "info");

fos.close();

fis.close();

}

}

// 自定义的文件空目录异常

class FileNotFoundRuntimeException extends RuntimeException
{

private static final long serialVersionUID =
1L;

public FileNotFoundRuntimeException(String string)
{

//
覆盖父类构造函数

super(string);

}

}

// 创建一个类,实现过滤器作用(suffix 后缀、末尾)

class suffixFilter implements FilenameFilter
{

// 设置一个字符串存储构造函数里面传进来的条件

private String suffix;

public suffixFilter(String suffix)
{

this.suffix = suffix;

}

// 通过条件返回过滤的结果

public boolean accept(File arg0,
String name) {

// TODO 自动生成的方法存根

return name.endsWith(suffix);

}

}

ObjectOutputStream 对象序列化 将 Java 对象的基本数据类型和图形写入
OutputStream。可以使用 ObjectInputStream 读取(重构)对象。通过在流中使用文件可以实现对象的持久存储。

只能将支持
java.io.Serializable 接口的对象写入流中。

1.构造函数

ObjectOutputStream()
为完全重新实现 ObjectOutputStream 的子类提供一种方法,让它不必分配仅由 ObjectOutputStream 的实现使用的私有数据。

ObjectOutputStream(OutputStream out)
创建写入指定 OutputStream 的 ObjectOutputStream。

2.实例

//读取对象

public static void inputObject(File file) throws Exception,
IOException {

ObjectInputStream ois = new ObjectInputStream(new FileInputStream("file"));

person p =
(person)ois.readObject();

System.out.println(p.getName()+":"+p.getAge());

}

//存储对象

public static void outputObject(File file) throws IOException,
FileNotFoundException {

ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("file"));

oos.writeObject(new person("wangcai",33));

oos.close();

}

3.

类实现接口Serializable中显示序列号

类中静态变量不能被序列存储

transient
修饰变量为瞬态,不能被序列化

====================File文件读写和异常处理代码练习====================

* 通过字符流读取一个文件打印在控制台上,并保存在另一个位置。并演示IOException异常处理方法。

*/

public class FileWriterDemo
{

public static void main(String[] args)
{

FileReader fr = null;

FileWriter fw = null;

File file = new File("E:\\", "test.txt");

File wfile = new File("E:\\FileWreader\\test.txt");

if (!file.isFile())

throw new RuntimeException("文件不存在,请输入正确的文件路径!");

try {

fr = new FileReader(file);

fw = new FileWriter(wfile);

char[] ch = new char[1024];

int len;

while ((len = fr.read(ch))
!= -1) {

System.out.println(new String(ch,
0, len));

fw.write(ch,
0, len);

fw.flush();

}

} catch (FileNotFoundException e)
{

e.printStackTrace();

} catch (IOException e)
{

e.printStackTrace();

} finally {

if (fw != null)

try {

fw.close();

} catch (IOException e)
{

// TODO 自动生成的
catch 块

e.printStackTrace();

}

if (fr != null)

try {

fr.close();

} catch (IOException e)
{

// TODO 自动生成的
catch 块

e.printStackTrace();

}

}

}

}

====================缓冲区代码练习====================

/*

* 通过字符流缓冲区读取(一次读取一行)写出一个文件打印在控制台上,并保存在另一个位置。并演示IOException异常处理方法。

*/

public class FileWriterDemo
{

public static void main(String[] args)
{

BufferedReader br = null;

BufferedWriter bw = null;

File file = new File("E:\\", "test.txt");

File wfile = new File("E:\\FileWreader\\test.txt");

if (!file.isFile())

throw new RuntimeException("文件不存在,请输入正确的文件路径!");

try {

br = new BufferedReader(new FileReader(file));

bw = new BufferedWriter(new FileWriter(wfile));

String str;

while ((str = br.readLine())
!= null) {

System.out.println(str);

bw.write(str);

bw.flush();

}

} catch (FileNotFoundException e)
{

e.printStackTrace();

} catch (IOException e)
{

e.printStackTrace();

} finally {

if (bw != null)

try {

bw.close();

} catch (IOException e)
{

// TODO 自动生成的
catch 块

e.printStackTrace();

}

if (br != null)

try {

br.close();

} catch (IOException e)
{

// TODO 自动生成的
catch 块

e.printStackTrace();

}

}

}

}

====================字节流代码练习====================

/*

* 用字节流将一张照片复制到另一个地方。

*/

public class FileOutputStreamDemo
{

public static void main(String[] args) throws IOException
{

FileInputStream fis = new FileInputStream("E:\\001.jpg");

FileOutputStream fos = new FileOutputStream("E:\\FileOutputStreams\\001.jpg");

byte[] b = new byte[1024];

int len;

while ((len = fis.read(b))
!= -1) {

//
System.out.println(new String(b,0,len));

fos.write(b,
0, len);

fos.flush();

}

fos.close();

fis.close();

}

}

====================System.in代码练习====================

public class System_inDemo
{

public static void main(String[] args) throws IOException
{

// 读取字符数组,当一次性大于数组时会分多次输出

InputStream is =
System.in;

byte[] bytes = new byte[10];

int len =
0;

String str;

while ((len = is.read(bytes))
!= -1) {

str = new String(bytes,
0, len);

System.out.println(str);

}

}

}

====================读取配置文件代码练习====================

/*

* 实例:纪录一个软件的试用次数,运行超过5次则提示“你已使用5次,请购买正版!”并关闭该软件。

*

*/

public class Pdemo
{

public static void main(String[] args) throws IOException
{

// 调用配置文件,查看使用次数

find();

// 程序运行代码

int x =
7;

int y =
4;

int z = add(x, y);

System.out.println(z);

}

private static void find() throws IOException
{

// 查看书用次数,大于5次提示信息,不大于5次 记录次数。

File file = new File("E:\\add\\countinto", "addcount.Properties");

// 判断并创建

if (!file.exists())
{

File filepath = file.getParentFile();

filepath.mkdirs();

file.createNewFile();

}

Properties prop = new Properties();

FileInputStream fis = new FileInputStream(file);

prop.load(fis);

// Set<Entry<Object,Object>> set = prop.entrySet();

// for(Entry<Object,Object> e : set)

// System.out.println(e.getKey()+"="+e.getValue());

String V = prop.getProperty("count");

Integer count;

// V=null,则表示没用过,赋值0次。

if (V == null)

V =
0 + "";

count =
Integer.parseInt(V);

count++;

if (count >
5)

throw new RuntimeException("您的试用次数已经到达5次,请购买正版!");

prop.setProperty("count", count + "");

// FileOutputStream fos =
new FileOutputStream(file); //

// 每次覆盖上次内容,没有使用次数记录时间

FileOutputStream fos = new FileOutputStream(file, true);//
每次继续写入,可以看到记录时间

prop.store(fos, "info");

fos.close();

fis.close();

}

private static int add(int x, int y)
{

// 定义一个功能,加法

return x + y;

}

}

====================分割合并文件代码练习====================

/*

* 完成一个文件的分割和合成。E:\SequenceInputStream\\test.wmv,分解成50m的文件+配置文件。合成源文件D:\demo\0.wmv

*

*/

public class SequenceInputStreamDemo
{

public static void main(String[] args) throws IOException
{

//
分割

// disswver();

//
合并

merge();

}

private static void merge() throws IOException
{

File file = new File("E:\\SequenceInputStream");

FileInputStream fis = null;

File[] files = file.listFiles(new myFilenameFilter(".Properties"));

if (files.length !=
1)

throw new RuntimeException("配置文件个数不对!");

fis = new FileInputStream(files[0]);

Properties prop = new Properties();

prop.load(fis);

Integer num =
Integer.parseInt(prop.getProperty("counts"));

File[] fileparts = file.listFiles(new myFilenameFilter(".wmv"));

if (fileparts.length != num)

throw new RuntimeException("合并文件个数不对!应该是" + num + "个");

ArrayList<FileInputStream> arr = new ArrayList<>();

for (int i =
0; i < num; i++)
{

arr.add(new FileInputStream(fileparts[i]));

}

Enumeration<FileInputStream> e =
Collections.enumeration(arr);

SequenceInputStream sis = new SequenceInputStream(e);

byte[] bytes = new byte[1024
* 1024 * 5];

int len =
0;

FileOutputStream fos = new FileOutputStream("E:\\FileReader\\" + prop.getProperty("name"));

while ((len = sis.read(bytes))
!= -1) {

fos.write(bytes,
0, len);

fos.flush();

}

fos.close();

fis.close();

sis.close();

}

private static void disswver() throws IOException {

/*

*
分割1.一个输入获取,关联三个输出。

*/

int count =
0;

File file = new File("E:\\SequenceInputStream", "test.wmv");

if (!file.isFile())

throw new RuntimeException("文件不存在!");

BufferedInputStream buffis = new BufferedInputStream(new FileInputStream(file));

BufferedOutputStream buffos = null;

byte[] bytes = new byte[1024
* 1024 * 5 * 10];

int len =
0;

while ((len = buffis.read(bytes))
!= -1) {

buffos = new BufferedOutputStream(

new FileOutputStream("E:\\SequenceInputStream\\testpart" + count + ".wmv"));

buffos.write(bytes,
0, len);

count++;

}

buffos = new BufferedOutputStream(

new FileOutputStream("E:\\SequenceInputStream\\testPart" + count + ".Properties"));

String name = file.getName();

int counts = count;

Properties prop = new Properties();

prop.setProperty("name", name);

prop.setProperty("counts", "" + count);

prop.store(buffos, "Info");

buffos.close();

}

}

class myFilenameFilter implements FilenameFilter
{

private String my;

public myFilenameFilter(String my)
{

super();

this.my = my;

}

public boolean accept(File file,
String s) {

return s.endsWith(my);

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: