1.字符输出流:Writer
public abstract class Write
extends Object
implements Appendable,Closeable.Flushable
public interface Appendable {
public Appendable
append(
char c)
throws IOException;
public Appendable
append(CharSequence csq)
throws IOException;
public Appendable
appenf(CharSequence csq,
int start,
int end)
throws IOException;
}
public void write(
char[] cbuf)
throws IOException;
public void write(String str)
throws IOException;
Write是一个抽象类,如果想要实例化,应该使用FileWriter子类
import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
public static void main(String args[])
throws Exception {
File file =
new File(
"路径");
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
Writer out =
new FileWriter(file);
String str =
"测试程序";
out.write(str);
out.close();
}
2.字符输入流:Reader
public abstract class Reader
extends Object
implements Readable,Closeable
public int read(
char[] cbuf)
throws IOException
//返回值:表示读取的数据长度,如果已经读取到结尾返回-1
import java.io.File;
import java.io.FileReader;
import java.io.Reader;
public static void main(String args[])
throws Exception {
File file =
new File(
"文件路径");
if (file.exists()) {
Reader in =
new FileReader(file) ;
char data[] =
new char[
1024];
int len = in.read(data);
in.close();
System.out.println(
new String(data,
0,len));
}
}
3.字节流与字符流的区别
字节流与字符流最大的区别在于:
1)字节流直接与终端进行数据交互; 2)字符流需要将数据经过缓冲区处理后,才可以输出;
没有close的后果的区别:
1)使用OutputStream输出数据时,即时最后没有关闭输出流,内容也可以正常输出 2)使用的是字符输出流,如果不关闭,那么表示在缓冲区之中处理的内容不会被强制性的清空,所以就不会输出数据 //注意,如果有特殊情况,不能关闭字符输出流,可以使用flush()方法强制清空缓冲区 //直接可以用对象调用,格式:对象名称.flush();
使用区别:
1)一般开发之中,对于字节数据处理是比较多的,例如:图片、音乐、电影、文字之类 2)对于字符流来说,最好的是可以进行中文处理,如果是字节,可能会造成混乱 //建议,如果没有中文问题,建议使用字节流
转载请注明原文地址: https://ju.6miu.com/read-1202850.html