先来看看一个IO流的总体概况:
1:先来看看FileInputStream和FileOutputStream的用法:字节流的用法示例
public static void main(String[] args) {
//数据写入文件,这里加了中文涉及到乱码问题
String a = "javaIO 流";
FileOutputStream fo = null;
FileInputStream fi = null;
try {
fo = new FileOutputStream("1.txt");
byte[] bstr = a.getBytes("UTF-8"); //这里统一用UTF-8格式进行写入操作防止乱码的发生
fo.write(bstr);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if(fo != null){
fo.close();
fo = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
//从文件中读取数据
File file = new File("1.txt");
try {
fi = new FileInputStream(file);
byte[] buffer = new byte[1024];
int len = fi.read(buffer); //从byte数组中读取一定长度的数据如果不加buffer的话会出现乱码原因是read()方法跟系统平台的编码格式有关
String re = new String(buffer,0,len,"UTF-8"); //规定编码格式为UTF-8防止读取的时候有乱码的发生
System.out.println(re);
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}finally {
if(fi != null){
try {
fi.close();
fi = null;
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
2:再来看看FileRead和FileWriter的用法:字符流的用法
public static void main(String[] args) {
//字符输出流
FileWriter fw = null;
try {
fw = new FileWriter("2.txt");
fw.write(a + 2);
if(fw != null){
fw.close();
fw = null;
}
} catch (IOException e) {
e.printStackTrace();
}
//从文件中读取数据:字符输入流
File f = new File("2.txt");
try {
fReader = new FileReader(f);
char[] buf = new char[1024];
int len = fReader.read(buf);
String res = new String(buf,0,len);
System.out.println(res);
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}finally {
if(fReader != null){
try {
fReader.close();
} catch (IOException e) {
e.printStackTrace();
}
fReader = null;
}
}
}