#IO流:操作文件的内容(附带示例小程序)
1、字节流:
输入流 -读 : InputStream
输出流 -写: OutputStream
package com.xuedao.inputstream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class TheMainClass {
/**
* 操作文件中的内容 IO流
* 字节流:
* 输入流 读 InputStream
* 输出流 写 OutputStream
* 转化流:将字符流转化为字节流
* @param args
*/
public static void main(String[] args) {
writeToFile();
}
/**
* 往文件中写数据
*/
public static void writeToFile() {
// 创建文件对象
File file = new File("E:\\xuedao\\24th\\javaSE\\file\\b.txt");
if(file.exists()) {
file.delete();
}
OutputStream out = null;
try {
file.createNewFile();
//获取文件输出流对象
out = new FileOutputStream(file);
//将数据写入到输出流
out.write("你好,我是你爸!\r\n".getBytes());
out.write("你妈在哪?".getBytes());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
if(out != null) {
out.close();
}
} catch (Exception e2) {
// TODO: handle exception
}
}
}
/**
* 读取数据
*/
public static void readFile() {
// 创建文件对象
File file = new File("E:\\xuedao\\24th\\javaSE\\file\\a.txt");
if(!file.exists()) {
return;
}
InputStream in = null;
try {
// 获取输入流对象
in = new FileInputStream(file);
// 创建一个byte[]来接收数据
byte[] b = new byte[1024];
// 创建一个度量
int len = -1;
// 创建一个字符串接收所有数据
StringBuilder sb = new StringBuilder();
//用b接收数据
while((len = in.read(b)) != -1) {
//将字节码数据转化为字符串,添加到字符串末尾
sb.append(new String(b, 0, len));
}
System.out.println(sb);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
if(in != null) {
in.close();
}
} catch (Exception e2) {
// TODO: handle exception
}
}
}
}
2、字符流:
输入流:Reader
输出流: Writer
package com.xuedao.reader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
public class TheMainClass {
/**
* 字符流
* 输入流:Reader
* 输出流: Writer
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
File file = new File("E:\\xuedao\\24th\\javaSE\\file\\b.txt");
write(file);
}
// 读
public static void read(File file) throws IOException {
Reader in = new FileReader(file);
char[] c = new char[1024];
int l = -1;
StringBuilder sb = new StringBuilder();
while((l = (in.read(c))) != -1) {
sb.append(c, 0, l);
}
System.out.println(sb);
in.close();
}
// 写
public static void write(File file) throws IOException {
Writer out = new FileWriter(file);
out.write("床前明月光\r\n");
out.write("疑是地上霜\r\n");
out.close();
}
}