Reader类常用的方法
- int read()
- int read(char[] c);
- read(char[] c,int off, int len)
- void close
子类InputStreamReader常用的构造方法 - InputStreamReader(InputStream in)
- InputStreamReader(InputSream in,String charseName)
public static void main(String[] args) {
System.out.println(readFile("E:/文件/test2.txt"));
}
public static String readFile(String path) {
File f = new File(path);
FileReader fr=null;
String str=null;
try {
fr=new FileReader(f);
char[] c = new char[(int) f.length()];
fr.read(c);
str = new String(c);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return str;
}
BufferedReader
为了提高字符流读取文本文件的效率,我们可以使用BufferedReader类。BufferedReader类是Reader类的子类,它带有缓冲区,按行读取内容。
public static void main(String[] args) {
BufferedReader br=null;
Reader fr=null;
FileInputStream fis=null;
try {
fis=new FileInputStream("E:/文件/test3.txt");
fr=new InputStreamReader(fis);
br = new BufferedReader(fr);
String str=null;
while ((str = br.readLine()) != null) {
System.out.println(str);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
br.close();
fr.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Writer类
Writer类常用方法:
- write(String str)
- write(String str,int off,int len)
- void close()
- void flush()
子类OutputStreamWriter常用的构造方法
- OutputStreamWriter(OutputStream out)
- OutputStreamWriter(OutputStream out,String charsetName)
public static void main(String[] args) {
Writer fw = null;
try {
System.out.println(System.getProperty("file.encoding"));
fw = new FileWriter("E:/文件/test3.txt");
String str = "好好学习!";
fw.write(str);
fw.write(str, 0, 2);
fw.flush();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Writer类同样有BufferedWriter类
public static void main(String[] args) {
String str = "浔阳江头夜送客,枫叶荻花秋瑟瑟。主人下马客在船,举酒欲饮无管弦。醉不成欢惨将别,别时茫茫江浸月。";
writeFiel(str, "E:/文件/test5.txt", false);
}
public static void writeFiel(String str, String path, boolean isAppend) {
FileWriter fw=null;
BufferedWriter bw = null;
try {
fw=new FileWriter(path,isAppend);
bw = new BufferedWriter(fw);
bw.write(str);
bw.flush();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}