Java IO操作最主要的是下面五个类:
1. File类(对文件本身)
2. InputStream类(字节流读入)
3. OutputStream类(字节流流出)
4. Reader(字符流读入)
5. Writer(字符流出)
需要注意的是,对字节的操作同样可以对字符进行操作,对字符的操作一般不对字节进行操作。
我们开始实现Java IO操作最简单的一些操作:
1.创建文件夹:
package stydy;
import java.io.*;
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
File f=new File("H:/IO练习");
f.mkdir(); //这句话是创建文件夹
}
}
2.创建文件:File.createNewFile 抛出两类异常,一类为IOException,一类为SecurityException
File f=new File("H:/IO练习/1.txt");
try {
f.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
3.列出文件夹内的所有文件(不含子目录):
public static void main(String[] args) {
File f=new File("H:/实习生");
String[] a=f.list();
for (int i = 0; i < a.length; i++) {
System.out.println(a[i]);
}
}
4.列出文件夹内的所有文件(含子目录):采用递归
package stydy;
import java.io.*;
public class Test {
public static void main(String[] args) {
Tool a=new Tool();
a.MyList("H:/实习生", 0);
}
}
class Tool{
public void MyList(String parent,int deep){
File f=new File(parent);
String[] a=f.list();
for(int i=0;i<a.length;i++){
for(int j=0;j<deep;j++){
System.out.print(" ");
}
if(deep>0) System.out.print("-");
System.out.println(a[i]);
File child=new File(parent,a[i]);
if(child.isDirectory()){
MyList(child.getPath(),deep+1);
}
}
}
}
package stydy;
import java.io.*;
public class Test {
public static void main(String[] args) {
File f=new File("H:/IO练习/1.txt");
FileInputStream fis = null;
try {
fis = new FileInputStream(f);
byte[] b=new byte[1024];
int n;
if((n=fis.read(b))!=-1){
String a=new String(b,0,n);
System.out.println(a);
}
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
6.字节流出:一定要记得finally关闭文件!!注意,此时会覆盖掉原有文件!
package stydy;
import java.io.*;
public class Test {
public static void main(String[] args) {
File f=new File("H:/IO练习/1.txt");
FileOutputStream fos = null;
try {
fos=new FileOutputStream(f);
String a="莫愁前路无知己,\r\n天下谁人不识君。";
try {
fos.write(a.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally{
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
小练习:图片复制
package study;
import java.io.*;
public class Copy {
public static void main(String[] args) {
File from=new File("H:/IO练习/1.jpg");
File to=new File("D:/1.jpg");
FileInputStream fis=null;
FileOutputStream fos=null;
int n;
byte[] b=new byte[1024];
try {
fis = new FileInputStream(from);
fos = new FileOutputStream(to);
while((n=fis.read(b))!=-1){
fos.write(b);
}
} catch (Exception e) {
e.printStackTrace();;
}finally{
try {
fis.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}