用File创建动态文件夹时用的是绝对路径,但是我想用相对路径创建文件夹,不知道如何创建,能告诉我么?

解决方案 »

  1.   

    相对路径一般是服务器路径 如你的服务器起装到E盘 他上传的文件就跑到E盘了 ! 你可以这样 
    String filePath = servlet.getServletContext().getRealPath("/"); //取当前系统路径
    File f=new File(filePath +"\\homeweb\\images\\a.txt");这样的话 你的项目放到那个盘他都不会把文件传错地址!
      

  2.   

    那如果就只是在java文件里使用,而不用到所谓的servlet的话,那么代码又该如何书写呢?
      

  3.   

    String filePath = servlet.getServletContext().getRealPath("/"); //取当前系统路径一般这个路径是你的项目下 你在加上你的具体上传的文件夹名字!
    file就是你从页面获取的客户端图片资料 !这种类型的 org.apache.struts.upload.FormFile  file;filePath =filePath +"\\pic\\house\\sale\\";//在系统路径上加上你的项目下专门放上传图片的位置String time= *****;获取日期的方法 自己写 想要返回的time是这样的字符串 "2006-05"
    String size = Integer.toString(file.getFileSize()) + "bytes";
    if (file.getFileSize() >= 20500)
    {
    return "";
    }//检查图片大小不超过20KB
    int i = fname.lastIndexOf(".");
    String str = "";
    if (i != -1)
    {
    str = fname.substring(i);
    }//获取文件后缀 我记得有个更好的方法 不过记得不太清楚了!if ((".jpg").equals(str) || (".gif").equals(str) || (".bmp").equals(str))//检验后缀名字是否是你允许的类型
    {
    InputStream in = file.getInputStream();
    fname = id + x + str;//重新命名图片 
    new File(path +time).mkdir();//创建 time 文件夹 
    new File(path +time+"\\"+ id).mkdir();//创建 ID 文件夹 要不要看你
    OutputStream out = new FileOutputStream(path + time +"\\"+ id + "\\" + fname);//上传图片

    out.close();
    in.close();
    file.destroy();
    }
    else
    {
    return "";
    }
    System.out.println(id + "\\" + fname);
    return time+"\\"+id + "\\" + fname;//返回新的图片名字!
    }
      

  4.   

    int bytesRead = 0;
    byte[] buffer = new byte[8192];
    while ((bytesRead = in.read(buffer, 0, 8192)) != -1)
    {
    out.write(buffer, 0, bytesRead);
    }//忘记加了!!!!!!11
    out.close();
    in.close();
    file.destroy();