Java IO学习笔记三
InputStreamReader
构造函数
常用方法
实例
package IO;
import java.io.*;
/**
* Created by chenjiabing on 17-5-24.
*/
public class demo4 {
public static void main(String args[]) {
File file = new File("/tmp" + File.separator + "test" + File.separator + "test.txt");
InputStreamReader inputStreamReader = null;
try {
inputStreamReader = new InputStreamReader(new FileInputStream(file)); //初始化
char[] c = new char[(int) file.length()]; //创建数组
try {
int len = inputStreamReader.read(c); //将内容读取到数组中
System.out.println(len);
for (int i = 0; i < c.length; i++) {
System.out.print(c[i]);
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally {
if(inputStreamReader!=null)
{
try {
inputStreamReader.close(); //关闭
}catch (IOException e)
{
e.printStackTrace();
}
}
}
}
}
OutputStreamWriter
构造函数
常用方法
实例
package IO;
import java.io.*;
/**
* Created by chenjiabing on 17-5-24.
*/
public class demo5 {
public static void main(String[] args)
{
File file=new File("/tmp"+File.separator+"test"+File.separator+"test.txt");
OutputStreamWriter outputStreamWriter=null;
try {
outputStreamWriter=new OutputStreamWriter(new FileOutputStream(file,true));
String str="陈加兵\n";
int data=48;
String name="chenjiabing";
try {
outputStreamWriter.write(str);
outputStreamWriter.write(data);
outputStreamWriter.write(name,0,2); //写入字符串的一部分
}catch (IOException e)
{
e.printStackTrace();
}
}catch (FileNotFoundException e)
{
e.printStackTrace();
}finally {
if(outputStreamWriter!=null)
{
try {
outputStreamWriter.flush();
outputStreamWriter.close();
}catch (IOException e)
{
e.printStackTrace();
}
}
}
}
}
参考文章