Java Io 字符流

Java Io 字符流包含:

1. InputStreamReader  它是由byte流解析为char流,并且按照给定的编码解析。

2. OutputStreamWrite  它是char流到byte流的转换,并且按照给定的编码处理。

事例代码如下:

package com.dcz.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter; public class ReaderWriterDemo { public static void main(String[] args) throws Exception { InputStream fileInputStream = new FileInputStream("D:\\reader.txt");
// 编码为文本文件的自身的编码格式,否则乱码
InputStreamReader isr = new InputStreamReader(fileInputStream, "gbk"); File writeFile = new File("D:\\writer.txt");
if(!writeFile.exists()){
writeFile.createNewFile();
}
OutputStream fileOutputStream = new FileOutputStream(writeFile);
OutputStreamWriter osw = new OutputStreamWriter(fileOutputStream, "gbk"); /* int c;
while((c = isr.read()) != -1){
System.out.print((char)c);
}*/ char[] charer = new char[2 * 1024];
int c;
while((c = isr.read(charer, 0, charer.length)) != -1){
osw.write(charer, 0, charer.length);
fileOutputStream.flush();
}
osw.close();
isr.close();
} }

3. FileReader

4. FileWriter

这两个流读取文本文件会更方便

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

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

		File writeFile = new File("D:\\writer.txt");
if(!writeFile.exists()){
writeFile.createNewFile();
}
FileWriter fw = new FileWriter(writeFile);
int c;
char[] charer = new char[2 * 1024];
while((c = fr.read(charer, 0, charer.length)) != -1){
fw.write(charer, 0, charer.length);
fw.flush();
}
fw.close();
fr.close();
}

5. BufferedReader

6. BufferedWriter

缓冲输入/输出流,该流可以一行一行读取,一行一样写入

package com.dcz.io;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer; public class BufferReaderWriterDemo { public static void main(String[] args) throws Exception { // 读取文件,可以一次读取一行文件
File readerFile = new File("D:\\reader.txt");
InputStream fis = new FileInputStream(readerFile);
Reader reader = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(reader); // 写入文件,可以一次写入一行文件
File writerFile = new File("D:\\writer.txt");
if(!writerFile.exists()){
writerFile.createNewFile();
}
OutputStream fos = new FileOutputStream(writerFile);
Writer writer = new OutputStreamWriter(fos);
BufferedWriter bw = new BufferedWriter(writer); String str = "";
while((str = br.readLine()) != null){
bw.write(str);
bw.newLine();
bw.flush();
}
bw.close();
br.close(); } }
上一篇:android自定义文本框,后面带清空按钮


下一篇:C# 创建、更改Excel命名区域(NamedRange)