FileReader fr = null
try{
File file = new File("filename");
fr = new FileReader(file);
data = fr.read();
}catch (IOException e){
e.printStackTrace();
}finally{
if(fr != null){
try{
fr.close()
}catch(IOException e){
e.printStackTrace();
}
}
}
注意:
其他read方法:
File file = new File("filename");//file可以不存在
FileWriter fw = new FileWriter(file, append);//append表示追加或覆盖
fw.write(...);
fw.close();
//try...catch..finally略
File file = new File("filename");
FileInputStream fis = new FileInputStream(file);
byte[] buffer = new byte[5];
int len;
while((len = fis.read(buffer)) != -1){
...
}
fis.close();
...
byte[] buffer = new byte[5];
int len;
while((len = fis.read(buffer)) != -1){
fos.write(buffer, 0, len);//指定offset和length
}
...
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
//1.造文件
File srcFile = new File("filename1");
File destFile = new File("filename2");
//2.造流
//2.1 造节点流
FileInputStream fis = new FileInputStream(srcFile);
FileOutputStream fos = new FileOutputStream(destFile);
//2.2 造缓冲流
bis = new BufferedInputStream(fis);
bos = new BufferedOutputStream(fos);
//前面几项可合并到一起写
//3.复制的细节:读入、写出
byte[] buffer = new byte[10];
int len;
while ((len = bis.read(buffer)) != -1) {
bos.write(buffer, 0, len);
//bos.flush();刷新缓冲区
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//4.资源关闭
//关闭外层流的同时,会自动关闭内层流
if(bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
可以使用
String data;
While((data = br.readLine()) != null){
//data中不包含换行符,可主动换行
bw.newLine();
}
提供了字节流和字符流的转换,本身属于字符流
InputStreamReader isr = null;
OutputStreamWriter osw = null;
try {
isr = new InputStreamReader(new FileInputStream("filename1"), "utf-8");
osw = new OutputStreamWriter(new FileOutputStream("filename2"), "gbk");
char[] cbuf = new char[20];
int len;
while((len = isr.read(cbuf)) != -1){
String str = new String(cbuf, 0, len);
System.out.println(str);
osw.write(cbuf, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally...
原文:https://www.cnblogs.com/xiafrog/p/14290091.html