1.字符流
1.1输出流,即向指定文件写入信息
public class CharWrite {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
// 创建文件对象,给出文件路径
File file = new File(".\\test.txt");
// 判判改路径下是否存在该文件
if (!file.exists()) {
System.out.println("文件不存在,正在创建");
// 创建文件
file.createNewFile();
}
// 创建字符流输出
BufferedWriter bf = new BufferedWriter(new FileWriter(file));
// 输出文件内容
for (int i = 0; i < 4; i++) {
bf.write("Long way to go\r\n");
}
// 关闭文件
bf.close();
}
}
1.2输入流,即读文件
public class Filecharread {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
//创建文件对象,给出文件路径
File file = new File(".\\test.txt");
//若该路径下不存在此文件
if (!file.exists()) {
System.out.println("文件不存在");
}
FileReader fr = new FileReader(file);
char[] word = new char[10];
StringBuffer sf = new StringBuffer();
//当文件没有内容读取时,FileReader.read()返回-1,凭此判断文件是否读完文件
int a = fr.read(word);
while (a != -1) {
sf.append(new String(word));
//更新a和word的值
a = fr.read(word);
}
System.out.println(sf.toString());
fr.close();
}
}
2 字节流
2.1 输出流,即写入信息
public class Bytewrite {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
File file = new File(".\\test1.txt");
if(!file.exists())
{
file.createNewFile();
}
//创建字节输出流
FileOutputStream fop = new FileOutputStream(file);
String content = "你好啊";
//将一个字符串转为字节,写入文件
fop.write(content.getBytes());
fop.close();
}
}
2.2 读取字节流
public class Byteread {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
File file = new File(".\\test1.txt");
if (!file.exists()) {
System.out.println();
}
FileInputStream fip = new FileInputStream(file);
//给出每次读取多少个字节,一个中文2个字节
byte[] word = new byte[2];
StringBuffer sb = new StringBuffer();
int a = fip.read(word);
while (a != -1) {
sb.append(new String(word));
a = fip.read(word);
}
System.out.println(sb.toString());
fip.close();
}
}