赞
踩
——Java培训、Android培训、iOS培训、.Net培训、期待与您交流! ——
public abstract class Writer extends Object implements Appendable,Closeable,Flushable
写入字符流的抽象类,子类必须实现的方法仅有write(char[] ,int ,int)、flush()和close()。但是,多数子类将重写此定义的方法,以提供更高的效率和/或其他功能。
与OutputStream一样,对文件的操作使用FileWriter来完成,此类的构造方法如下:
代码演示:
package com.joe.io;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
/**
* 字符输出流格式: Writer/FileWriter out = new FileWriter()
* try{}
* catch{}
* finally{}
*
* 思路: 1、创建输出流对象 2、用write方法往里面写数据 3、关闭流对象
*
* 注意事项:一定要关闭流
*
* @author joe
*
*/
public class FileWriterTest {
public static void main(String[] args) {
write();
System.out.println("success!");
}
public static void write() {
// 创建一个流对象
Writer fw = null;
try {
// true表示追加输出
fw = new FileWriter("introduce.doc", true);
fw.write("abcderf");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fw != null)
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

public abstract class Reader extends Object implements Closeable,Readable
使用FileReader类进行实例化操作,FileReader类中的构造方法定义如下:
代码演示:
package com.joe.io;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
/**
* 读取一个文件,并打印在控制台上
* 字符输入流格式: Reader/FileReader fr = new FileReader()
* try{}
* catch{}
* finally{}
*
* 思路:
* 1、创建输出流对象
* 2、定义一个字符,用来保存实际读取的字符数,-1表示没有数据
* 3、创建一个字符数组,用来定义每次读取数据的长度
* 4、创建一个StringBuilder缓冲区,用来接收数据
* 5、输出读取数据
* 6、关闭流对象
*
* 注意事项:一定要关闭流
* @author joe
*
*/
public class FileReaderTest {
public static void main(String[] args) {
FileReader fr = null;
try {
fr = new FileReader("introduce.doc");
//创建一个字符数组定义一次读取的长度
char[] ch = new char[1024];
int len = 0;
//没有数据的时候,返回-1
while ((len = fr.read(ch)) != -1) {
System.out.println(new String(ch, 0, len));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
//关闭流对象
if(fr!=null)
fr.close();
} catch (IOException e) {
System.out.println(e.toString());
}
}
}
}

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。