1、File的簡(jiǎn)單操作
public class IOTest01 {
public static void main(String[] args) {
String path = "D:/temp/";
// File temp =File.createTempFile("asa", ".temp", new File(path));創(chuàng)建臨時(shí)文件
// temp.deleteOnExit();刪除臨時(shí)文件
testFile01(path);
}
public static void testFile01(String path){
if(path!=null){
File file = new File(path);
if(file.isDirectory()){//判斷是否是文件夾
System.out.println(path+"是文件夾");
//File[] roots = File.listRoots();//獲取盤(pán)符所有目錄[C:\, D:\, E:\, F:\, H:\]
//System.out.println(Arrays.toString(roots));
String[] files = file.list();//獲取文件夾下面所有文件名,包括文件夾的名稱(chēng)
System.out.println(Arrays.toString(files));
testFile02(file,"");
}else if(file.isFile()){//判斷是否是文件
System.out.println(path+"是文件");
System.out.println(file.getName()+"能否可寫(xiě):"+file.canWrite());
System.out.println(file.getName()+"能否可讀:"+file.canRead());
System.out.println(file.getName()+"長(zhǎng)度:"+file.length());
//file.renameTo(new File())刪掉原來(lái)的文件,并把文件創(chuàng)建、復(fù)制到新的文件
System.out.println(file.getName()+"改名:"+file.renameTo(new File("D:/temp/a/newName.txt")));
//file.delete();刪除文件
}else{
System.out.println(path+"不存在");
boolean flag = file.mkdir();//創(chuàng)建文件夾,必須保證父目錄存在,否則創(chuàng)建不成功
System.out.println(flag?"創(chuàng)建成功":"創(chuàng)建失敗");
if(!flag)file.mkdirs();//創(chuàng)建文件夾,如果整個(gè)文件夾鏈上有不存在的,則都會(huì)創(chuàng)建
}
}
}
public static void testFile02(File file,String kg){
File[] files2 = file.listFiles();
// File[] files2 = file.listFiles(new FilenameFilter(){
// public boolean accept(File dir, String name) {//此處dir和name代表遍歷出的文件目錄和文件名
// return new File(dir,name).isFile() && name.lastIndexOf(".txt")>0;
// }});listFiles(new FilenameFilter(){});此方法用來(lái)過(guò)濾文件
if(kg==null || kg.equals("")){kg = "|----";}else{kg=kg.replace("|", " ");kg=kg.replace("-", " ");kg = kg+"|----";}
for(File f : files2){
if(f.isDirectory()){//如果是文件夾
System.out.println(kg+f.getName());
testFile02(f,kg);
}else{
System.out.println(kg+f.getName());
}
}
}
}
2、節(jié)點(diǎn)流與功能流
2.1、節(jié)點(diǎn)流
字節(jié)流:InputStream、OutputStream、FileInputStream、FileOutputStream
字符流:Writer、Reader、FileWriter、FileReader
字節(jié)流:InputStream、OutputStream、FileInputStream、FileOutputStream
public class IOTest02 {
public static void main(String[] args) {
String path1 = "D:/temp/";
String path2 = "D:/temp2/";
//inputStreamTest(path1);
//outputStreamTest(path2);
//copyFile(path1,path2);
copyDir(path1,path2);
}
public static void inputStreamTest(String path){
File file = new File(path);
InputStream ins =null;
try {
ins = new FileInputStream(file);
byte[] b = new byte[512];
int len = 0;
while(-1!=(len = ins.read(b))){
System.out.println(new String(b,"GBK"));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
if(ins!=null){try {ins.close();} catch (IOException e) {e.printStackTrace();}}
}
}
public static void outputStreamTest(String path){
File file = new File(path);
OutputStream outs =null;
try {
outs = new FileOutputStream(file);
String value = "safsag阿薩德剛?cè)齻€(gè)色";
outs.write(value.getBytes());
outs.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
if(outs!=null){try {outs.close();} catch (IOException e) {e.printStackTrace();}}
}
}
public static void copyFile(String srcPath,String destPath){
File srcFile = new File(srcPath);
File destFile = new File(destPath);
copyFile(srcFile,destFile);
}
public static void copyFile(File srcFile,File destFile){//拷貝文件
InputStream ins = null;
OutputStream outs =null;
try {
ins = new FileInputStream(srcFile);
outs = new FileOutputStream(destFile);//默認(rèn)是不追加的,若為new FileOutputStream(destFile,true),則為追加
byte[] b = new byte[512];
int len = 0;
while(-1!=(len=ins.read(b))){
outs.write(b, 0, len);
}
outs.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
if(ins!=null){try {ins.close();} catch (IOException e) {e.printStackTrace();}}
if(outs!=null){try {outs.close();} catch (IOException e) {e.printStackTrace();}}
}
}
public static void copyDir(String srcPath,String destPath){//拷貝文件夾及其內(nèi)容
File srcFile = new File(srcPath);
File destFile = new File(destPath);
if(!srcFile.isDirectory()){
System.out.println("原地址不是正確的文件夾地址");
return;
}else if(!destFile.isDirectory()){
destFile.mkdirs();
}
File destRoot = new File(destPath,srcFile.getName());
destRoot.mkdir();
copyDirHelper(srcFile,destRoot);
File[] files = srcFile.listFiles();
}
public static void copyDirHelper(File srcFile,File destFile){
File[] files = srcFile.listFiles();
for(File file:files){
if(file.isDirectory()){
(new File(destFile.getAbsolutePath(),file.getName())).mkdir();
copyDirHelper(file,new File(destFile.getAbsolutePath(),file.getName()));
}else if(file.isFile()){
copyFile(file,new File(destFile.getAbsolutePath(),file.getName()));
}
}
}
}
2.2、字符流Writer、Reader、FileWriter、FileReader
public class IOTest03 {
public static void main(String[] args) {
String path1 ="D:/temp/caililiang2.txt";
String path2 ="D:/temp/caililiang5.txt";
//readerTest(path1);
//writerTest(path2);
copyFile(path1,path2);
}
public static void readerTest(String path){
File file = new File(path);
Reader read =null;
try {
read = new FileReader(file);
char[] c = new char[512];
int len =0;
while(-1!=(len = read.read(c))){
System.out.println(new String(c));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
if(read!=null){try {read.close();} catch (IOException e) {e.printStackTrace();}}
}
}
public static void writerTest(String path){
File file = new File(path);
Writer writer =null;
try {
writer = new FileWriter(file);
String value = "safsdgdsfgsdfgsd";
writer.write(value);
writer.append("=====sdsdgdsf");
writer.flush();
} catch (Exception e) {
} finally{
if(writer!=null){try {writer.close();} catch (IOException e) {e.printStackTrace();}}
}
}
public static void copyFile(String srcpath,String destpath){//拷貝文件
File srcFile = new File(srcpath);
File destFile = new File(destpath);
copyFile(srcFile,destFile);
}
public static void copyFile(File srcFile,File destFile){//拷貝文件
Reader read =null;
Writer writer =null;
try {
read = new FileReader(srcFile);
writer = new FileWriter(destFile);
int len = 0;
char[] c = new char[512];
while(-1!=(len = read.read(c))){
writer.write(c,0,len);
}
writer.flush();
} catch (Exception e) {
} finally{
if(read!=null){try {read.close();} catch (IOException e) {e.printStackTrace();}}
if(writer!=null){try {writer.close();} catch (IOException e) {e.printStackTrace();}}
}
}
}
2.3、字節(jié)緩沖流(BufferedInputStream、BufferedOutputStream)與字符緩沖流(BufferedReader、BufferedWriter)
public static void main(String[] args) {
File srcFile = new File("D:/temp/caililiang2.txt");
File destFile = new File("D:/temp/caililiang5.txt");
//copyFile(srcFile,destFile);
copyFile2(srcFile,destFile);
}
public static void copyFile(File srcFile,File destFile){//拷貝文件
InputStream ins = null;
OutputStream outs =null;
try {
//字節(jié)緩沖流:加快流操作速度
//new BufferedInputStream(new InputStream(new File(""))),
//new BufferedOutputStream(new OutputStream(new File("")))
ins = new BufferedInputStream(new FileInputStream(srcFile));
outs = new BufferedOutputStream(new FileOutputStream(destFile));//默認(rèn)是不追加的,若為new FileOutputStream(destFile,true),則為追加
byte[] b = new byte[512];
int len = 0;
while(-1!=(len=ins.read(b))){
outs.write(b, 0, len);
}
outs.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
if(ins!=null){try {ins.close();} catch (IOException e) {e.printStackTrace();}}
if(outs!=null){try {outs.close();} catch (IOException e) {e.printStackTrace();}}
}
}
public static void copyFile2(File srcFile,File destFile){//拷貝文件
BufferedReader read =null;
BufferedWriter writer =null;
try {
//字符緩沖流:提供了新方法BufferedReader.readLine()讀取一行,BufferedWriter.newLine()換行
//new BufferedReader(new FileReader(srcFile)),new BufferedWriter(new FileWriter(destFile))
read = new BufferedReader(new FileReader(srcFile));
writer = new BufferedWriter(new FileWriter(destFile));
String line = null;
while(null!=(line=read.readLine())){
writer.write(line);
writer.newLine();//等同writer.append("\r\n");
}
writer.flush();
} catch (Exception e) {
} finally{
if(read!=null){try {read.close();} catch (IOException e) {e.printStackTrace();}}
if(writer!=null){try {writer.close();} catch (IOException e) {e.printStackTrace();}}
}
}
}
2.4、轉(zhuǎn)換流(InputStreamReader,OutputStreamWriter)
轉(zhuǎn)換流InputStreamReader(InputStream,String)把字節(jié)輸入流轉(zhuǎn)換到字符輸入流
轉(zhuǎn)換流OutputStreamWriter(InputStream,String)把字節(jié)輸出流轉(zhuǎn)換到字符輸出流
public class IOTest05 {
public static void main(String[] args) {
File srcFile = new File("D:/temp/caililiang2.txt");
File destFile = new File("D:/temp/caililiang5.txt");
copyFile(srcFile,destFile);
}
public static void copyFile(File srcFile,File destFile){//拷貝文件
BufferedReader read =null;
BufferedWriter writer =null;
try {
//轉(zhuǎn)換流InputStreamReader(InputStream,String)把字節(jié)輸入流轉(zhuǎn)換到字符輸入流
//轉(zhuǎn)換流OutputStreamWriter(InputStream,String)把字節(jié)輸出流轉(zhuǎn)換到字符輸出流
read = new BufferedReader(new InputStreamReader(new FileInputStream(srcFile),"GB2312"));
writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(destFile),"GB2312"));
String line = null;
while(null!=(line=read.readLine())){
writer.write(line);
writer.newLine();//等同writer.append("\r\n");
}
writer.flush();
} catch (Exception e) {
} finally{
if(read!=null){try {read.close();} catch (IOException e) {e.printStackTrace();}}
if(writer!=null){try {writer.close();} catch (IOException e) {e.printStackTrace();}}
}
}
}
2.5、字節(jié)數(shù)組流(ByteArrayInputStream、ByteArrayOutputStream)
public class IOTest06 {
public static void main(String[] args) {
File srcFile = new File("D:/temp/178_IO_重點(diǎn)流_總結(jié).mp4");
File destFile = new File("D:/temp/178_IO.mp4");
try {
byte[] datas = fileToBytes(srcFile);
System.out.println(datas.length);
BytesTofile(datas,destFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static byte[] fileToBytes(File file) throws FileNotFoundException{
InputStream ins = new BufferedInputStream(new FileInputStream(file));
ByteArrayOutputStream bais = new ByteArrayOutputStream();//字節(jié)數(shù)組輸出流
byte[] b = new byte[20];
int len = 0;
try {
while((len = ins.read(b))!=-1){
bais.write(b, 0, len);
}
bais.flush();
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
ins.close();
bais.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return bais.toByteArray();
}
public static void BytesTofile(byte[] b,File file) throws FileNotFoundException{
InputStream bais = new BufferedInputStream(new ByteArrayInputStream(b));//字節(jié)數(shù)組輸入流
OutputStream out =new BufferedOutputStream(new FileOutputStream(file));
byte[] bb = new byte[20];
int len = 0;
try {
while((len = bais.read(bb))!=-1){
out.write(bb, 0, len);
}
out.flush();
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
out.close();
bais.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
2.6、基本數(shù)據(jù)類(lèi)型+String處理流(DataInputStream、DataOutputStream),把數(shù)據(jù)+類(lèi)型存放在流中
public class IOTest07 {
public static void main(String[] args) {
File srcFile = new File("D:/temp/caililiang2.txt");
File destFile = new File("D:/temp/caililiang5.txt");
try {
//dataOutputStreamTest(destFile);
dataInputStreamTest(destFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public static void dataOutputStreamTest(File file) throws FileNotFoundException{
DataOutputStream dis = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(file)));
try {
dis.writeUTF("caililiang");
dis.writeInt(123);
dis.writeBoolean(false);
} catch (IOException e) {
e.printStackTrace();
} finally{
try {dis.close();} catch (IOException e) {e.printStackTrace();}
}
}
public static void dataInputStreamTest(File file) throws FileNotFoundException{
DataInputStream dis = new DataInputStream(new BufferedInputStream(new FileInputStream(file)));
try {
System.out.println(dis.readUTF());
System.out.println(dis.readInt());
System.out.println(dis.readBoolean());
} catch (IOException e) {
e.printStackTrace();
}
}
}
2.7、引用類(lèi)型(對(duì)象)處理流 (ObjectInputStream、ObjectOutputStream) 把數(shù)據(jù)+類(lèi)型存放在流中
public class People implements java.io.Serializable{//實(shí)現(xiàn)Serializable接口,就會(huì)告訴JVM這個(gè)類(lèi)是要被序列化的類(lèi),Serializable是個(gè)空接口
private String name;
private int age;
private transient String address;//transient使屬性“透明”,不能被序列化
public People(String name, int age, String address) {
super();
this.name = name;
this.age = age;
this.address = address;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
public class IOTest08 {
public static void main(String[] args) {
People p1 = new People("caililiang",25,"hubei");
People p2 = new People("caililiang2",25,"hubei2");
People p3 = new People("caililiang3",25,"hubei3");
File destFile = new File("D:/temp/caililiang5.txt");
try {
//objectOutputStreamTest(destFile,p1,p2,p3);
objectInputStreamTest(destFile);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void objectOutputStreamTest(File file,People ... ps) throws FileNotFoundException, IOException{//People ... ps,表示多個(gè)People類(lèi)型的參數(shù)
ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(file)));
for(People p :ps){
out.writeObject(p);
}
out.flush();
out.close();
}
public static void objectInputStreamTest(File file) throws IOException, ClassNotFoundException{
ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(new FileInputStream(file)));
Object obj1 =in.readObject();
Object obj2 =in.readObject();
Object obj3 =in.readObject();
if(obj1 instanceof People){
People p1 =(People) obj1;
System.out.println(p1.getName());
System.out.println(p1.getAge());
System.out.println(p1.getAddress());//地址為transient修飾,未被序列化
}
if(obj2 instanceof People){
People p2 =(People) obj2;
System.out.println(p2.getName());
System.out.println(p2.getAge());
System.out.println(p2.getAddress());//地址為transient修飾,未被序列化
}
in.close();
}
}
2.8、Closeable接口,實(shí)現(xiàn)同時(shí)關(guān)閉多個(gè)流
public class FileUtil {
public static void close(Closeable ... io){//同時(shí)關(guān)閉多個(gè)流
for(Closeable i :io){
try {
if(i!=null){i.close();}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static <T extends Closeable> void closeAll(T ... io){//泛型實(shí)現(xiàn)關(guān)閉多個(gè)實(shí)現(xiàn)了Closeable接口的流
for(Closeable i :io){
try {
if(i!=null){i.close();}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
2.9、打印流(printStream)
public class IOTest10 {
public static void main(String[] args) throws FileNotFoundException {
test2();
}
public void test1() throws FileNotFoundException{
System.out.println("hello World !!!");
PrintStream out = System.out;//輸出流 控制臺(tái)輸出
PrintStream err = System.err;
InputStream in = System.in;//輸入流 鍵盤(pán)輸入
out.println("caililiang");
err.println("caililiang");
PrintStream out2 = new PrintStream(new BufferedOutputStream(new FileOutputStream(new File("D:/temp/caililiang5.txt"))));
Scanner sc = new Scanner(in);
System.out.println("請(qǐng)輸入:");
out2.println(sc.nextLine());
out2.flush();
out2.close();
}
public static void test2() throws FileNotFoundException{
//setOut重定向標(biāo)準(zhǔn)輸出流
//setIn重定向標(biāo)準(zhǔn)輸入流
System.setIn(new BufferedInputStream(new FileInputStream(new File("D:/temp/caililiang2.txt"))));
Scanner sc = new Scanner(System.in);//Scanner掃描輸入
System.out.println(sc.nextLine());//此時(shí)標(biāo)準(zhǔn)輸入流變?yōu)槲募斎? System.setOut(new PrintStream(new BufferedOutputStream(new FileOutputStream(new File("D:/temp/caililiang5.txt")))));
System.out.println("asfsdfss");
System.out.append("sfs121");
System.out.flush();
System.out.close();
System.out.append("sfs121");//關(guān)閉之后不生效
}
}
2.10、文件的分割與合并(利用RandomAccessFile實(shí)現(xiàn))
public class FileSplit {
private File file;//分割的文件
private int count;//分割的塊數(shù)
private long blockSize;//每塊的大小
private long fileLength;//文件的總大小
private String destPath;//分割后的文件存放目錄
private Vector<String> names;//每個(gè)文件塊的名稱(chēng)
public FileSplit(File file){}
public FileSplit(File file,long blockSize,String destPath){
this.file = file;
this.blockSize = blockSize;
this.destPath = destPath;
init();
}
public void init(){
fileLength = file.length();
count = (int) Math.ceil(fileLength*1.0/blockSize);
names = new Vector<String>();
for(int i=0;i<count;i++){
names.add(file.getName()+i);
}
}
public void splitDetail(){
RandomAccessFile ran = null;
OutputStream out = null;
long begainPos =0;
long readCount =blockSize;
int len =0;
byte[] b = new byte[20];
try {
ran = new RandomAccessFile(file,"r");
for(int i=0;i<count;i++){
out = new BufferedOutputStream(new FileOutputStream(new File(destPath+names.get(i))));
ran.seek(begainPos);
readCount =blockSize;
len=0;
while((len=ran.read(b))!=-1 && readCount>0){
if(len>readCount){out.write(b, 0, (int)readCount);}else{
out.write(b, 0, (int)len);
}
readCount=readCount-len;
}
begainPos+=blockSize;
out.flush();
out.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
try {ran.close();} catch (IOException e) {e.printStackTrace();}
}
}
public void fileMerge(String destPath2) throws FileNotFoundException{
File destFile = new File(destPath2);
InputStream in = null;
OutputStream out = new BufferedOutputStream(new FileOutputStream(destFile,true));
int len =0;
byte[] b = new byte[20];
for(int i=0;i<count;i++){
try {
len = 0;
in = new BufferedInputStream(new FileInputStream(new File(destPath+names.get(i))));
while((len = in.read(b))!=-1){
out.write(b, 0, len);
}
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
try {in.close();} catch (IOException e) {e.printStackTrace();}
}
}
try {out.flush();out.close();} catch (IOException e) {e.printStackTrace();}
}
public long getBlockSize() {
return blockSize;
}
public void setBlockSize(long blockSize) {
this.blockSize = blockSize;
}
public String getDestPath() {
return destPath;
}
public void setDestPath(String destPath) {
this.destPath = destPath;
}
}