java 对文件及(夹)的操作

package com.jy.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;

import org.apache.log4j.Logger;

@SuppressWarnings("unchecked")
public class FileUtil {

private static Logger logger = Logger.getLogger(FileUtil.class);

/*
* 新建文件(夹)
*
* @param path 目标文件路径
*/
public static boolean create(String path,String fileName){
boolean flag = false ;
try{
File file = new File(path,fileName);
if(path.endsWith(".txt")){
if(!file.exists()){
file.createNewFile();
}else{
flag = true ;
logger.info("文件名已存在!");
}
}else{
if(!file.exists()){
file.mkdir();
}else{
flag = true ;
logger.info("文件已存在!");
}
}
}catch(Exception e){

}
return flag ;
}

/*
* 文件写入
*
* @param path 目标文件
*/
public static void write(String path,String content){
try {
File file = new File(path);
/*OutputStream out = new FileOutputStream(file);//字节流写入文件
byte[] buffer = content.getBytes();
out.write(buffer);*/
Writer out = new FileWriter(file);//字符流写稿文件
out.write(content);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}

/*
* 文件读取
*
* @param path 目标文件
* 字节流与字符流的区别
* 字节流在读写文件时,直接与文件交互
* 字节流 ---> 文件
* 字符流在读写文件时,先写在缓冲区中,在写在文件中
* 字符流 ---> 内存 ---> 文件
* 操作中文中,最好使用字符流,因为一个汉字占用两个字节
*/
public static void read(String path){
try {
File file = new File(path);
/*InputStream in = new FileInputStream(file);//字节流文件读取
byte[] buffer = new byte[(int)file.length()];// 开辟空间接收读取的内容
int len = in.read(buffer);
System.out.println(new String(buffer,0,len));*/
Reader in = new FileReader(file);//字符流文件读取
char[] buffer = new char[(int)file.length()];
int len = in.read(buffer);
System.out.println(new String(buffer,0,len));
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}

/*
* 遍历文件(夹)
* @param path 目标文件路径
*/
@SuppressWarnings("deprecation")
public static List list(String path){
List list = new ArrayList();
File file = new File(path);
File[] f = file.listFiles();
String extName = "";
String url = "" ;
String fileName = "" ;
int total ;
String big ="";
String date = "" ;
int m=0,n=0;
if(f != null){
for(int i=0;i<f.length;i++){
HashMap map = new HashMap();
if(f[i].isDirectory()){
url = URLEncoder.encode(f[i].getAbsolutePath());
fileName = f[i].getName();
total = f[i].listFiles().length;
map.put("total", total);
big = "--";
++m;
}else{
url = URLEncoder.encode(f[i].getAbsolutePath());
fileName = f[i].getName();
total = 0;
try {
big = getFileSize(new FileInputStream(f[i]).available());
}catch (Exception e) {
e.printStackTrace();
}
++n;
}
if(i+1==f.length){
map.put("m", m);
map.put("n", n);
}
extName = getExtName(fileName);
date = DateUtil.DateFormat(f[i].lastModified());
map.put("url", url);
map.put("big", big);
map.put("date", date);
map.put("extName", extName);
map.put("fileName", fileName);
list.add(map);
}
}
return list;
}

/*
* 文件(夹)重命名
* @param path 目标文件
* @param name 文件名
*/
public static void rename(String path,String name){
/*File file = new File(path);*/
}

/*
* 复制文件(夹)到一个目标文件夹
*
* @param oldpath 当前文件的绝对路径及文件名
* @param newpath 复制文件的到新绝对路径及文件名
*/
public static void copy(String oldpath,String newpath){
try{
File oldFile = new File(oldpath);
File newFile = new File(newpath);
if(!oldFile.exists()){
return ;
}
if(!newFile.exists()){
newFile.mkdir();
}
if(oldFile.isFile()){
File file = new File(newFile.getPath()+File.separator+oldFile.getName());
//复制文件到目标文件
InputStream ins = new FileInputStream(oldFile);
FileOutputStream out = new FileOutputStream(file);
byte[] buffer = new byte[1024*512] ;
int length ;
while((length = ins.read(buffer)) != -1){
out.write(buffer, 0, length);
}
ins.close();
out.flush();
out.close();
}else{
newFile.mkdir();
for(File f:oldFile.listFiles()){
copy(oldpath,newpath);
}
}
}catch(Exception e){
e.printStackTrace();
}
}

/*
* 将文件(夹)移动到令一个文件夹
*
* @param oldpath 当前文件的绝对路径及文件名
* @param newpath 复制文件的到新绝对路径及文件名
*/
public void moveFile(String oldPath, String newPath) {
copy(oldPath, newPath);
delete(oldPath);
}

/*
* 删除文件(夹)
*
* @param path 文件的绝对路径及文件名
*/
public static boolean delete(String path){
boolean flag = false ;
try{
File file = new File(path) ;
if(file.exists()){
if(file.isFile()){
file.delete();
flag = true ;
}else{
for(File f:file.listFiles()){
delete(f.getAbsolutePath());
}
file.delete();
flag = true ;
}
}else{
flag = false;
}
}catch(Exception e){
e.printStackTrace();
}
return flag;
}

/*
* 获取文件后缀名
*/
public static String getExtName(String fileName){
String extName = fileName.substring(fileName.lastIndexOf(".")+1).toLowerCase();
String result = "";
if("txt".equals(extName)){
result = "<img src=\"pic/txt.gif\">";
}else if("html".equals(extName)){
result = "<img src=\"pic/ie.gif\">";
}else if("gif".equals(extName)){
result = "<img src=\"pic/img.gif\">";
}else if("chm".equals(extName)){
result = "<img src=\"pic/chm.gif\">";
}else if("bmp".equals(extName)){
result = "<img src=\"pic/bmp.gif\">";
}else if("java".equals(extName)){
result = "<img src=\"pic/java.gif\">";
}else if("mdb".equals(extName)){
result = "<img src=\"pic/mdb.gif\">";
}else if("mp3".equals(extName)||"rm".equals(extName)||"rmvb".equals(extName)){
result = "<img src=\"pic/media.gif\">";
}else if("xls".equals(extName)){
result = "<img src=\"pic/excel.gif\">";
}else if("ppt".equals(extName)){
result = "<img src=\"pic/ppt.gif\">";
}else if("doc".equals(extName)){
result = "<img src=\"pic/word.gif\">";
}else if("pdf".equals(extName)){
result = "<img src=\"pic/pdf.gif\">";
}else if("rar".equals(extName)||"zip".equals(extName)){
result = "<img src=\"pic/rar.gif\">";
}else if("xml".equals(extName)){
result = "<img src=\"pic/xml.gif\">";
}else{
result = "<img src=\"pic/folder.gif\">";
}
return result;
}

/*
* 设置文件类型
*/
public static String getContentType(String path) {
String extName = path.toLowerCase();
String result = "";
if (extName.endsWith("txt")) {
result = "text/plain";
}
if (extName.endsWith("gif")) {
result = "image/gif";
}
if (extName.endsWith("jpg")) {
result = "image/jpeg";
}
if (extName.endsWith("jpeg")) {
result = "image/jpeg";
}
if (extName.endsWith("jpe")) {
result = "image/jpeg";
}
if (extName.endsWith("zip")) {
result = "application/zip";
}
if (extName.endsWith("rar")) {
result = "application/rar";
}
if (extName.endsWith("doc")) {
result = "application/msword";
}
if (extName.endsWith("ppt")) {
result = "application/vnd.ms-powerpoint";
}
if (extName.endsWith("xls")) {
result = "application/vnd.ms-excel";
}
if (extName.endsWith("html")) {
result = "text/html";
}
if (extName.endsWith("htm")) {
result = "text/html";
}
if (extName.endsWith("tif")) {
result = "image/tiff";
}
if (extName.endsWith("tiff")) {
result = "image/tiff";
}
if (extName.endsWith("pdf")) {
result = "application/pdf";
}
return result;
}

/*
* 获取文件大小
*/
public static String getFileSize(long f){
String size = "";
DecimalFormat df = new DecimalFormat("#.00");
if(f<1024){
size = df.format((double) f) + "B";
}else if(f<1048576){
size = df.format((double) f /1024) + "k";
}else if(f<1073741824){
size = df.format((double) f /1048576) + "M";
}else{
size = df.format((double) f /1073741824) + "G";
}
return size;
}

public static void main(String args[]){
/*FileUtil.list("c:/create/123");
String str = "123243242434343";
FileUtil.create("c:/create/123/123.txt",str);*/
FileUtil.read("c:/create/123/123.txt");
}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值