Java IO流类结构图,转载自 https://www.cnblogs.com/zhaoyanjun/p/6292384.html
在这里不对所有的类进行举例,只对FileReader/FileWriter, 文本输入输出
FileInputStream,FileOutputStream: 字节输入输出
下面是具体的代码示例:
package com.main;
import java.io.*;
import java.nio.charset.Charset;
public class FileTest {
public void readTextFile(String fileName){
FileReader f = null;
try {
f= new FileReader(fileName);
char[] a=new char[1024];
while (f.read(a)>0){
String strTemp = new String(a);
System.out.println(getStringCharSet(strTemp));
}
f.close();
} catch (Exception e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
try {
f.close();
} catch (IOException e1) {
// TODO 自动生成的 catch 块
e1.printStackTrace();
}
}
}
public void readTextFile2(String fileName){
File f = new File(fileName);
String str = null;
FileInputStream in = null;
StringBuilder strB = null;
try {
in = new FileInputStream(f);
byte[] b = new byte[1024];
Charset charset = Charset.forName("utf8");
strB = new StringBuilder();
while (in.read(b)>0){
str= new String(b,charset);
strB.append(str);
}
System.out.println(strB);
in.close();
} catch (Exception e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
try {
in.close();
} catch (IOException e1) {
// TODO 自动生成的 catch 块
e1.printStackTrace();
}
}
}
//返回utf-8 编码的字符串
public String getStringCharSet(String strValue){
Charset charset = Charset.forName("utf8");
byte[] b = strValue.getBytes();
String c= new String(b,charset);
return c;
}
//写入文本
public void writelog(String strValue,String sFileName){
FileWriter w = null;
try {
w = new FileWriter(sFileName,true);
w.write(strValue+"\n");
w.close();
} catch (IOException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
try {
w.close();
} catch (IOException e1) {
// TODO 自动生成的 catch 块
e1.printStackTrace();
}
}
}
//以字节形式写入
public void writelog2(String strValue,String sFileName){
File f = null;
FileOutputStream out = null;
f= new File(sFileName);
try {
out = new FileOutputStream(f,f.exists());
strValue = strValue + "\n";
byte[] b = strValue.getBytes();
out.write(b);
out.close();
} catch (Exception e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
try {
out.close();
} catch (IOException e1) {
// TODO 自动生成的 catch 块
e1.printStackTrace();
}
}
}
}
package com.main;
public class Main {
public static void main(String[] args) {
// TODO 自动生成的方法存根
FileTest f = new FileTest();
String sFileName = "E:\\Desktop\\Temp\\01.txt";
f.writelog2("好久不见", sFileName);
//f.readTextFile("E:\\Desktop\\Temp\\01.txt");
/*StringBuilder c= new StringBuilder();
c.append("Hello");
f.test(c);
System.out.print(c);*/
}
}