黑马程序员技术交流社区
标题: java基础---IO [打印本页]
作者: 周发建 时间: 2016-3-28 09:42
标题: java基础---IO
一、IO[size=16.0000pt](一)概述IO流:输入流Reader、输出流Writer
用于处理设备之间的数据传输
字符流 = 字节流 + 码表
InputStream/OutputStream
|--FileInputStream/FileOutputStream
|--BufferedInputStream/BufferedOutputStrem
Reader/Writer
|--InputStreamReader/OutputStreamWriter字节流到字符流桥梁(可指定编码)
|--FileReader/FileWriter 字节流到字符流的便捷类,系统默认编码
|--BufferedReader/BufferedWriter 字符缓冲区,增强读写效率【装饰】
|--LineNumberReader(readLine();newline())
write(); 写,输出
read();读,输入
[size=16.0000pt](二)练习:复制文件//标准的复制文本文件的方法
public static void copyTextFile(File srcFile, File tarFile){
FileReader in = null;
FileWriter out = null;
try {
in = new FileReader(srcFile);
out = new FileWriter(tarFile);
char[] buf = new char[BUFFER_SIZE];
int len = 0;
while((len = in.read(buf))!=-1){
out.write(buf, 0, len);
out.flush();
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
[size=16.0000pt](三)装饰设计//装饰设计,增强功能
public class MyBufferedReader extends Reader{
private Reader r;
public MyBufferedReader(Reader r){
this.r = r;
}
private int count = 0;
private int pos = 0;
private char[] buf = new char[1024];
@Override
public int read(char[] cbuf, int off, int len) throws IOException {
if(count == 0){
count = r.read(buf);
pos = 0;
if(count < 0){
return -1;
}
}
char ch = buf[pos++];
count--;
return ch;
}
public String readLine() throws IOException{
StringBuilder sb = new StringBuilder();
int ch = 0;
while((ch = this.read())!=-1){
if(ch == '\r'){
continue;
}
if(ch == '\n'){
return sb.toString();
}
sb.append((char)ch);
}
if(sb.length() > 0){
return sb.toString();
}
return null;
}
@Override
public void close() throws IOException {}
}
[size=16.0000pt](四)复制MP3//复制MP3
public static void copyMP3(File srcFile, File tarFile){
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream(srcFile);
out = new FileOutputStream(tarFile);
byte[] buf = new byte[BUFFER_SIZE];
int len = 0;
while((len = in.read(buf))!=-1){
out.write(buf, 0, len);
out.flush();
}
out.close();
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//键盘录入
BufferedReader bfr = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bfw = new BufferedWriter(new FileWriter("d://keyout.txt"));
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) |
黑马程序员IT技术论坛 X3.2 |