字节流
public class IODemo01 {
//异常抛出
public static void main(String[] args) throws IOException {
//构造器 创建流
//InputStream is=new FileInputStream("D:/hehe.txt");
//建立联系
File src=new File("D:/test.txt");
//构建流
InputStream is=new FileInputStream(src);
//读入
//read() 一个字节一个字节读取 返回读入的内容 如果没有了返回-1
int num=is.read();
System.out.println((char)num);
num=is.read();
System.out.println((char)num);
num=is.read();
System.out.println((char)num);
num=is.read();
System.out.println(num);
//关闭
is.close();
}
}
public class IOTest {
public static void main(String[] args) {
//建立联系
File sc = new File("C:/haha/test.txt");
//构造流
InputStream in = null;
//异常捕捉
try {
in = new FileInputStream(sc);
byte[] arr=new byte[1024];
int len=-1;
while((len=in.read(arr))!=-1){
System.out.println(new String(arr,0,len));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if (in!=null) {
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
- 拷贝文件(字节流)
public class IOTest3 {
public static void main(String[] args) {
InputStream in=null;
OutputStream out=null;
try {
in=new FileInputStream("C:/haha/test.txt");
out=new FileOutputStream("C:/haha/test2.txt");
byte[] arr=new byte[1024];
int len=-1;
while((len=in.read(arr))!=-1){
out.write(arr,0,len);
}
//刷出
out.flush();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
//关闭流 后打开的先关闭
try {
out.close();
if(out!=null){
}
if (in!=null) {
in.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
字符流
拷贝文件
public class CharTest {
public static void main(String[] args) {
Reader reader = null;
Writer writer = null;
try {
reader = new FileReader("C:/haha/test.txt");
writer = new FileWriter("C:/haha/hehe.txt");
// char[] arr = new char[1024];
// int num = -1;
// while ((num = reader.read(arr)) != -1) {
// writer.write(arr, 0, num);
// }
//字符流可以直接读取字符串
int num = -1;
while ((num = reader.read()) != -1) {
writer.write(num);
}
// 刷出
writer.flush();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
// 关闭流
try {
if (writer != null) {
writer.close();
}
if (reader != null) {
reader.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}