字节流 字符流
输入 InputStream Reader
输出 OutputStream Writer
字节流的文件包括图片,音乐等,字符流文件主要是文本文件
字节流文件输入输出
// File f = new File("d:\\input.txt");
// File out = new File("d:\\output.txt");
//也可以是图片文件
File f = new File("d:\\IMG_1526.JPG");
File out = new File("e:\\IMG_1526.JPG");
FileInputStream is = null;
FileOutputStream os=null;
// System.out.println(f.getAbsolutePath());
try {
os = new FileOutputStream(out);
is = new FileInputStream(f);
byte[] bytes = new byte[512];
int n = 0;
while ((n = is.read(bytes)) != -1) {
//String s = new String(bytes, 0, n);
//System.out.println(s);
//os.write(s.getbytes());
os.write(bytes);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
is.close();
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
字符流文件输入输出
File f = new File("d:\\input.txt");
File out = new File("d:\\output.txt");
FileReader is = null;
FileWriter os=null;
// System.out.println(f.getAbsolutePath());
try {
os = new FileWriter(out);
is = new FileReader(f);
char []a = new char[1024];
int n = 0;
while ((n = is.read(a)) != -1) {
//String s = new String(bytes, 0, n);
//System.out.println(s);
//os.write(s.getbytes());
os.write(a,0,n);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
is.close();
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
缓冲字符流主要针对string,可以一行一行的进行读取
BufferReader BufferWriter
File f = new File("d:\\input.txt");
File out = new File("d:\\output.txt");
FileReader is = null;
FileWriter os=null;
BufferedReader br=null;
BufferedWriter bw=null;
// System.out.println(f.getAbsolutePath());
try {
os = new FileWriter(out);
is = new FileReader(f);
br = new BufferedReader(is);
bw = new BufferedWriter(os);
String str="";
while ((str = br.readLine()) != null) {
//String s = new String(bytes, 0, n);
//System.out.println(s);
//os.write(s.getbytes());
bw.write(str+"\r\n");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
br.close();
bw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}