您的位置:首页 > 编程语言 > Java开发

java对文件实用操作

2008-07-28 14:29 381 查看
package batchdata;

import java.io.*;
import java.util.zip.ZipOutputStream;
import java.util.zip.ZipEntry;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.ArrayList;
import java.util.Vector;
import javax.swing.JTable;
import javax.swing.JTree;
import javax.swing.tree.TreeNode;
public class FileOperate {
/**
* @since
* @author caipc
*
*/
public FileOperate() {
}

/**
* 新建一个目录(文件夹),如果已经存在相同文件夹名,则先删除后,再创建
*
* @param filepath
*/
public static boolean newFolder(String filepath) {
boolean ok = false;
try {
String myfilepath = filepath.toString();
File myFilePath = new File(myfilepath);
if (myFilePath.exists()) {
delFolder(filepath);
myFilePath.mkdir();
ok = true;
} else {
myFilePath.mkdir();
ok = true;
}
} catch (Exception e) {
System.out.print("新建目录出错");
e.printStackTrace();

}
return ok;
}

/**
* 创建一个新的文件,并且向文件中写入内容
*
* @param filepathandname
* 有完整路径的新文件
* @param filecontent
* 向新建文件中写入的内容
*/
public static boolean newFile(String filepathandname, String filecontent) {
boolean flag = true;
try {
String filepath = filepathandname.toString();
File myFilePath = new File(filepath);
if (!myFilePath.exists()) {
myFilePath.createNewFile();
}
// FileWriter resultFile = new FileWriter(myFilePath,true);
// public FileWriter(File file,boolean append) throws IOException
// 注:append为true时,要在原有的文件中追加内容
// 默情况时为false 或者干脆不用第二个参数。如下所示
FileWriter resultFile = new FileWriter(myFilePath, true);
PrintWriter myFile = new PrintWriter(resultFile);
String strContent = filecontent;
myFile.write(strContent);
resultFile.close();
} catch (Exception e) {
System.out.println("新建文件出错");
e.getStackTrace();
flag = false;
}
return flag;
}

/**
* 删除指定文件目录中的指定文件
*
* @param filepathandname
*/
public static boolean delFile(String filepathandname) {
boolean ok = false;
try {

String filepath = filepathandname.toString();
File myDelFile = new File(filepath);
if (myDelFile.exists()) {

myDelFile.delete();
ok = true;
return ok;
}
} catch (Exception e) {
System.out.print("删除文件失败");
e.getStackTrace();
}
return ok;
}

/**
* 删除文件夹 ,包括文件夹中的所有的文件
*
* @param filepath
*/
public static void delFolder(String filepath) {
try {
String myFilePath = filepath.toString();
delAllFiles(myFilePath);
File myDelFolder = new File(myFilePath);
// System.out.print(myDelFolder);
myDelFolder.delete();

} catch (Exception e) {
System.out.print("删除空文件夹失败");
e.getStackTrace();
}
}

/**
* 删除指定目录及目录下所有文件
*
* @param filepath
*/
public static void delAllFiles(String folderpath) {
try {
String filepath = folderpath.toString();
File myDelAllFiles = new File(filepath);
if (!myDelAllFiles.exists()) {
return;
}
if (!myDelAllFiles.isDirectory()) {
return;
}
String[] fileList = myDelAllFiles.list();
File temp = null;
for (int i = 0; i < fileList.length; i++) {
temp = new File(filepath + File.separator + fileList[i]);
if (temp.isFile()) {
temp.delete();
}
if (temp.isDirectory()) {
delAllFiles(filepath + File.separator + fileList[i]);// 先删除文件夹里面的文件
delFolder(filepath + File.separator + fileList[i]);// 再删除空文件夹
}
}

} catch (Exception e) {
System.out.print("删除指定目录及目录下所有文件失败");
}
}

/**
* 从指定目录复制单个的文件到另一个目录中,同时改变文件的名字
*
* @param oldpath
* @param oldfilename
* @param newpath
* @param newfilename
* @return
*/

public static boolean fileCopy(String oldpath, String oldfilename,
String newpath, String newfilename) {
boolean ok = false;
try {
int bytesum = 0;
int byteread = 0;
String oldstr = oldpath + File.separator + oldfilename;
// String oldstr = oldpath + "//"+ oldfilename;
String newstr = newpath + File.separator + newfilename;
File oldfile = new File(oldstr);
// System.out.print(oldfile);
if (oldfile.exists()) {

InputStream inStream = new FileInputStream(oldstr);

File newfile = new File(newstr);
if (newfile.exists()) {
newfile.delete();
// newfile.createNewFile();
}
FileOutputStream fs = new FileOutputStream(newstr);
byte[] buffer = new byte[1024];
while ((byteread = inStream.read(buffer)) != -1) {
bytesum += byteread; // 字节数 文件大小
// System.out.println(bytesum);
fs.write(buffer, 0, byteread);
}
ok = true;
}
} catch (Exception e) {
e.getStackTrace();
System.out.print("复制文件失败");
}
return ok;
}

/**
* 复制一个文件夹(包括里面的所有文件)到另一个文件夹
*
* @param oldpath
* @param newpath
* @return
*/
public static boolean copyFolder(String oldpath, String newpath) {
boolean ok = false;
try {
if (!(new File(oldpath).exists())) {
System.out.print("要复制的文件夹不存在");
return ok;
} else {
File temp = null;
File newfolder = new File(newpath);
newfolder.mkdirs(); // 创建一个新的文件夹
String[] file = (new File(oldpath).list());
for (int i = 0; i < file.length; i++) {
if (file[i].endsWith(File.separator))
temp = new File(oldpath + file[i]);
else {
temp = new File(oldpath + File.separator + file[i]);
}
if (temp.isFile()) {
fileCopy(oldpath, temp.getName(), newpath, temp
.getName());
}
if (temp.isDirectory()) {
copyFolder(oldpath + File.separator + file[i], newpath
+ File.separator + file[i]);
}

}
ok = true;
}
} catch (Exception e) {
System.out.print("复制文件夹失败");
e.getStackTrace();
}
return ok;
}

/**
* 单个文件的移动
*
* @param oldpath
* @param filename
* @param newpath
*/
public static void moveFile(String oldpath, String filename, String newpath) {
String oldfile = oldpath + "//" + filename;
fileCopy(oldpath, filename, newpath, filename);
delFile(oldfile);
}

/**
* 单个文件的压缩
*
* @param path
* 要压缩的文件路径
* @param file
* 要压缩的文件的名字 压缩后的文件名和目录与原文件都相同,只是扩展名改为了".rar"
*/
public static int zipFile(String path, Vector<String> filnm) {
int ok = 0;
String rarfilenm = path + File.separator + "student.rar";
File f = new File(rarfilenm); // 文件扩展名也支持".zip"
if (!f.exists()) {
f.delete();
}
byte[] buf = new byte[1024];
int len;
try {
// FileOutputStream out=new FileOutputStream("d://temp//aa.zip");
ZipOutputStream zop = new ZipOutputStream(new FileOutputStream(
rarfilenm));// 设置压缩后的文件存放及文件名
Iterator iterator = filnm.iterator();
while (iterator.hasNext()) {
String filepath = path + File.separator + iterator.next();
System.out.println(filepath);
ZipEntry ze = new ZipEntry(filepath);// 找到要被压缩的文件,创建一个ZipEntry对象
File csvf = new File(filepath);
ze.setSize(csvf.length()); // 设置尺寸
ze.setTime(csvf.lastModified()); // 设置时间
zop.putNextEntry(ze);
InputStream is = new BufferedInputStream(new FileInputStream(
filepath));
while ((len = is.read(buf, 0, 1024)) != -1) {
zop.write(buf, 0, len);
}
is.close();
ok++;
}
zop.close();
} catch (IOException e) {
e.getStackTrace();
}
return ok;
}

/**
* 整个文件夹的压缩,名为:原文件夹名.rar 如果文件夹中有汉语名字的文件,可能会在解压缩时出现席圈错误,但是不影响各个文件中的内容
*
* @param path
* 压缩文件存放目录
* @param zippath
* 要压缩的文件夹路径
*
*/
public static int zipFolder(String path, String zippath) {
int success = 0;
File folder = new File(zippath);
if (!folder.isDirectory()) {
return 0;
}
try {
String zipname = path + File.separator + folder.getName() + ".rar";
byte[] buf = new byte[1024];
int len;
List fileList = fileNameList(folder);
InputStream is = null;
ZipOutputStream zop = new ZipOutputStream(new FileOutputStream(
zipname));
for (int i = 0; i < fileList.size(); i++) {
File f = (File) fileList.get(i);
if (f.getName().equals("Thumbs.db")) {
continue;
}
ZipEntry ze = new ZipEntry(f.getPath().toString());
ze.setSize(f.length());
ze.setTime(f.lastModified());
zop.putNextEntry(ze);
is = new BufferedInputStream(new FileInputStream(f));
while ((len = is.read(buf, 0, 1024)) != -1) {
zop.write(buf, 0, len);
}
is.close();
}
zop.close();
success = 1;
} catch (Exception e) {
e.getStackTrace();
}
return success;
}

/**
* 采用递归方法取到文件夹中所有的文件的路径,包括子文件夹中的文件
*
* @param folder
* @return
*/
public static List fileNameList(File folder) {
List filelist = new ArrayList();
File[] temp = folder.listFiles();
for (int i = 0; i < temp.length; i++) {
if (temp[i].isFile()) {
filelist.add(temp[i]);
}
if (temp[i].isDirectory()) {
filelist.addAll(fileNameList(temp[i]));
}
}
return filelist;
}

/**
* jpg 文件名修改将.jpg全部改成为.JPG
*
* @param args
*/
public static void doModify(String fromFolder, String toFolder) {
File fileFolder = new File(fromFolder);
File[] temp = fileFolder.listFiles();
for (int i = 0; i < temp.length; i++) {
if (temp[i].isFile()) {
String namestr = temp[i].getName();
String name = namestr.substring(0, namestr.indexOf("."));
String type = namestr.substring(namestr.indexOf(".") + 1);
String newname = name + ".JPG";
if ("jpg".equalsIgnoreCase(type)) {
fileCopy(fromFolder, namestr, toFolder, newname);
}

}
}

}

/**
* 将一个文件夹中的所有jpg文件压缩成指定宽度文件,放到另一个映射目录中
*
* @param oldpath
* @param newpath
* @return
*/
public static boolean compresAllPic(String oldpath, String newpath) {
boolean ok = false;
try {
if (!(new File(oldpath).exists())) {
System.out.print("要处理的文件夹不存在");
return ok;
} else {
File temp = null;
File newfolder = new File(newpath);
newfolder.mkdirs(); // 创建一个新的文件夹
String[] file = (new File(oldpath).list());
for (int i = 0; i < file.length; i++) {
if (file[i].endsWith(File.separator))
temp = new File(oldpath + file[i]);
else {
temp = new File(oldpath + File.separator + file[i]);
}
if (temp.isFile()) {
PictureDoWith.cutPicture(oldpath, temp.getName(),
newpath, temp.getName());
}
if (temp.isDirectory()) {
compresAllPic(oldpath + File.separator + file[i],
newpath + File.separator + file[i]);
}

}
ok = true;
}
} catch (Exception e) {
System.out.print("复制文件夹失败");
e.getStackTrace();
}
return ok;
}

/**
* vector文件夹的创建
*
* @param args
*/
public static boolean creatfolder(String path, Vector<String> sqls) {
boolean flag = false;
Iterator iterator = sqls.iterator();
while (iterator.hasNext()) {
flag = newFolder(path + File.separator + iterator.next());
}
return flag;
}

public static boolean creatDataFile(String dataLoc) {
boolean flag = false;
String schnm = dataLoc.substring(dataLoc.lastIndexOf(File.separator) + 1);
String path = new File(".").getAbsolutePath();
String datafile_stu =path.substring(0, path.length() - 1)+"batchdata/datafiles";
if (newFolder(datafile_stu)) {
File filelist = new File(dataLoc);
File[] files = filelist.listFiles();
for (int i = 0; i < files.length; i++) {
if (!files[i].getPath().endsWith(".db")) {
flag = writeDataFile(schnm, files[i]);
}
}
}
return flag;
}

public static boolean writeDataFile(String schnm, File file) {
boolean flag = false;
StringBuffer sb = new StringBuffer(2048);
String cc = file.getPath();
String clanm = cc.substring(cc.lastIndexOf(File.separator) + 1);
String path = new File(".").getAbsolutePath();
String datafile_stu =path.substring(0, path.length() - 1)+"batchdata/datafiles"
+ File.separator + schnm + "_" + clanm + "_student.csv";
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
if (!files[i].getPath().endsWith(".db")) {
String filepath = files[i].getName();
String usernm = filepath.substring(0, 8);
String stunam = filepath
.substring(8, filepath.lastIndexOf("."));
sb.append(schnm + ",");
sb.append(clanm + ",");
sb.append(usernm + ",");// 登录名
sb.append(stunam + ",");// 姓名
sb.append(usernm + "_pic.jpg");// 照片名
sb.append(System.getProperty("line.separator"));// 换行
}
}
flag = newFile(datafile_stu, sb.toString());
sb.delete(0, sb.length());
return flag;
}

public static boolean execSaveTable(JTable table, Object[] paths) {
boolean flag = false;
if (paths.length < 2) {
return false;
}
StringBuffer sb = new StringBuffer(4096);
String csvName = paths[0] + "_" + paths[1] + "_student.csv";
String path = new File(".").getAbsolutePath();
path =path.substring(0, path.length() - 1)+"batchdata/datafiles";
String filepath = path + File.separator + csvName;
File file = new File(filepath);
if (file.exists()) {
file.delete();
}
int rows = table.getRowCount();
int cols = table.getColumnCount();
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
sb.append(table.getValueAt(i, j) + ",");
}
sb.delete(sb.length() - 1, sb.length());
sb.append(System.getProperty("line.separator"));
}
if (newFile(filepath, sb.toString())) {
sb.delete(0, sb.length());
sb = null;
flag = true;
}
return flag;
}

public static boolean addFileConten(String fileN, String conten) {
boolean ok = false;
String path = new File(".").getAbsolutePath();
path =path.substring(0, path.length() - 1)+"batchdata";
String Inipath=path+File.separator+fileN;
try {
File file = new File(Inipath);
if (file.exists()) {
FileWriter resultFile = new FileWriter(file, true);
PrintWriter myFile = new PrintWriter(resultFile);
String strContent = conten
+ System.getProperty("line.separator");
myFile.write(strContent);
resultFile.close();
ok = true;
}
} catch (Exception e) {
e.printStackTrace();
}
return ok;
}

public static boolean datadelete() {
boolean ok = true;

String path = new File(".").getAbsolutePath();
path =path.substring(0, path.length() - 1)+"batchdata";
String deletpath = path+File.separator;
String[] folders = { "datafiles", "printfiles", "pictemp", "netimages" };
try {
for (int i = 0; i < folders.length; i++) {
File deletdate = new File(deletpath + folders[i]);
File[] datas = deletdate.listFiles();
for (int j = 0; j < datas.length; j++) {
if (datas[j].isDirectory()) {
delFolder(datas[j].toString());
} else {
datas[j].delete();
}
}
}
File initFile = new File(deletpath);
File[] inits = initFile.listFiles();
for (int i = 0; i < inits.length; i++) {
if (inits[i].getName().endsWith(".ini")) {
inits[i].delete();
}
}
} catch (Exception e) {
ok = false;
e.printStackTrace();
}
return ok;
}

public static void dataExport(JTree tree, String exportP) {
String path = new File(".").getAbsolutePath();
path =path.substring(0, path.length() - 1)+"batchdata";
String netimage = path+File.separator + "netimages";
String exportpath = exportP + "(导出)";
File file = new File(exportpath);
if (!file.exists()) {
file.mkdir();
}
RightDataPanel rdp = RightDataPanel.getinstance();
JTable table;
TreeNode root = (TreeNode) tree.getModel().getRoot();
Enumeration e = root.children();
while (e.hasMoreElements()) {
Object[] obj = new Object[2];
obj[0] = root;
obj[1] = e.nextElement();
table = rdp.init(obj);
creatExportFile(table, obj, exportpath);
}
copyFolder(netimage, exportpath);

}

public static void creatExportFile(JTable table, Object[] obj,
String exportpath) {
String fileN = exportpath + File.separator + obj[1].toString() + ".csv";
String separator = System.getProperty("line.separator");
String FILE_HEAD = "学生编号,登录密码,学生姓名,学生卡号,照片名称" + separator;
StringBuffer sb = new StringBuffer(128);
File csvfile = new File(fileN);
try {
if (!csvfile.exists()) {
csvfile.createNewFile();
}
newFile(fileN, FILE_HEAD);
for (int i = 0; i < table.getRowCount(); i++) {
sb.append(table.getValueAt(i, 2) + ",");
sb.append(table.getValueAt(i, 4) + ",");
sb.append(table.getValueAt(i, 3) + ",");
sb.append(table.getValueAt(i, 4) + ",");
sb.append(table.getValueAt(i, 5));
sb.append(separator);
newFile(fileN, sb.toString());
sb.delete(0, sb.length());
}
} catch (IOException e) {
e.printStackTrace();
}

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: