io的标准四个步骤
1:创建源
2:选择流
3:操作(读取)
4:关闭
文件字节输入流
package cn.com.io;
import java.io.*;
public class TestIo02 {
public static void main(String[] args) {
File file = new File("abc.txt");
InputStream is = null;
try {
is = new FileInputStream(file);
int tmp;
while((tmp = is.read()) != -1) {
System.out.println((char) tmp);
}
}catch(FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e) {
e.printStackTrace();
}finally {
try {
is.close();
}catch(IOException e) {
e.printStackTrace();
}
}
}
}
文件字节输出流
package cn.com.io;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
public class TestIo03 {
public static void main(String[] args) throws IOException {
//文件字节输出流
File file =new File("zxc.txt");
//file.delete();
OutputStream os = new FileOutputStream(file);
String str = "i like you!!";
byte[] bytes = str.getBytes();
os.write(bytes,0,bytes.length);
os.flush();
}
}
利用输入输出流拷贝文件
package cn.com.io;
import java.io.*;
public class TestIo04 {
public static void main(String[] args) {
copy("src/cn/com/io/TestIo01.java","TestIo01.txt");
}
public static void copy(String src,String dest) {
File srcfile = new File(src);
File destfile = new File(dest);
InputStream is = null;
OutputStream os = null;
try {
is = new FileInputStream(srcfile);
os = new FileOutputStream(destfile);
//操作
byte[] bytes = new byte[1024];
int tmp;
while((tmp = is.read(bytes)) != -1) {
os.write(bytes,0,tmp);
}
os.flush();
}catch(FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e) {
e.printStackTrace();
}finally {
//先打开的后关闭,后打开的先关闭
try {
if ( os != null) {
os.close();
}
}catch(IOException e) {
e.printStackTrace();
}
}
try {
if (is != null) {
is.close();
}
}catch(IOException e) {
e.printStackTrace();
}
}
}