Java IO

Posted by Alexander Wang on June 12, 2016

文件名分隔符跨平台

使用File类中的常量改写代码:

import java.io.*;
class hello{
    public static void main(String[] args) {
    	//File f=new File("D:\\hello.txt");	
        String fileName="D:"+File.separator+"hello.txt";
        File f=new File(fileName);
        try{
            f.createNewFile();
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
}

常用方法:

删除一个文件

if(f.exists()){
	f.delete();
	}

创建一个文件夹

f.mkdir();

列出指定目录的全部文件(包括隐藏文件):

String[] str=f.list();
for (int i = 0; i < str.length; i++) {
	System.out.println(str[i]);
}

向文件中写入字符串

		OutputStream out =new FileOutputStream(f);
        String str="你好";
        byte[] b=str.getBytes();
        out.write(b);
        out.close();

Creative Commons License
This work is licensed under a CC A-S 4.0 International License.