存取文件

// save文件;
    public static long saveFile(File file, String fileName, String filePath)
           throws Exception {
       if (file == null) {
           return 0;
       }
      
       File filepath = new File(filePath);
       if (!filepath.isDirectory())
           filepath.mkdirs();
       File filedesc = new File(filepath, fileName);
      
       return copyFile(file, filedesc);
    }

    // copy文件;
    public static long copyFile(File fromFile, File toFile) {
       long len = 0;

       InputStream in = null;
       OutputStream out = null;
       try {
           in = new FileInputStream(fromFile);
           out = new FileOutputStream(toFile);
           byte[] t = new byte[1024];
           int ii = 0;
           while ((ii = in.read(t)) > 0) {
              out.write(t, 0, ii);
              len += ii;
           }

       } catch (IOException e) {
           e.printStackTrace();

       } finally {
           if (in != null) {
              try {
                  in.close();
              } catch (Exception e) {
                  e.printStackTrace();
              }
           }

           if (out != null) {
              try {
                  out.close();
              } catch (Exception e) {
                  e.printStackTrace();
              }
           }

       }

       return len;
    }
    public static String getFileName(String filePath)
    {
    String str="";
    str=filePath.substring(filePath.lastIndexOf("/")+1,filePath.length());
    return str;
    }

// 删除文件
public static boolean delFile(String FolderPath, String fileName) {
if (FolderPath == null || "".equals(FolderPath)) {
System.out.println("文件夹路径为空");
return false;
}
if (fileName == null || "".equals(fileName)) {
System.out.println("文件名为空");
return false;
}
boolean flag = false;
File f1 = new File(FolderPath);
File[] f2 = f1.listFiles();
for (int i = 0; i < f2.length; i++) {
if (fileName.equals(f2[i].getName())) {
f2[i].delete();
System.out.println("删除" + FolderPath + "文件夹下的" + fileName
+ "文件成功");
flag = true;
}
}
return flag;
}

你可能感兴趣的:(文件)