Java 文件输入输出流File读取写入文件

1.获取文件路径、项目路径

如果做成jar包可以使用这种方式,这种方式可以取得该类的绝对路径

//取得该类的绝对路径
String location = 类名.class.getProtectionDomain().getCodeSource().getLocation().getPath();
//以下是获取jar包的上一级文件夹
 int startIndex = 0;
 if( endIndex == -1 ) {
	endIndex = location.lastIndexOf("classes");
 }
 文件夹路径 = location.substring(startIndex, endIndex);

普通不是jar包的反射获取

String path = class1.getClassLoader().getResource("").toString();
//file:/在这里这么做是为了消除开头的file://
int m = path.indexOf("/");
path = path.substring(m + 1);// 真正的路径

2.读取指定文件

//如果文件不存在则会抛异常
public static void main(String[] arg0){
        // 文件名称
        logFileName =  "-" + "2019-01-18" + ".txt";
        File f = new File(路径名称);
        String s="";
        InputStream in=null;
        try{
            in=new FileInputStream(f);
            //在这里设置每次读取多少个字符,不用特别大
            byte[] b = new byte[10];
            while(in.read(b)!=-1){
                s+=new String(b);
            }
            in.close();
        }catch(Exception e){
            e.printStackTrace();
        }
        System.out.println("content:"+s);
    }

3.写入文件

//如果文件不存在则会抛异常
public static void main(String[] arg0){
        // 文件名称
        logFileName =  "-" + "2019-01-18" + ".txt";
        File f = new File(路径名称);
        fileStream=new FileOutputStream(f, true);
        streamWriter=new OutputStreamWriter(fileStream);
        streamWriter.write("今天是个好日子心想的事儿都能成!"); 
        streamWriter.flush();
        streamWriter.close();
    }

猜你喜欢

转载自blog.csdn.net/zhaohan___/article/details/86522407