java代码对文件操作方法

package com.sdmc.media.util;


import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;


public class MyFileUtil {


private ArrayList<String> mListFile;
private int mCopyChunkSize;

public MyFileUtil() {
mListFile = new ArrayList<String>();
mListFile.clear();

mCopyChunkSize = 1024 * 1024 * 10;
}

public ArrayList<String> getFileList() {
return mListFile;
}

public void setCopyChunkSize(int size) {
mCopyChunkSize = size;
}


public static void mkDir(String path) {
File catchDir = new File(path);
if (!catchDir.exists()) {
catchDir.mkdirs();
catchDir.setWritable(true, false);
catchDir.setReadable(true, false);
}
}



public boolean copyFile(File src, File dest, boolean isdeletesrc) {
if (!src.exists()) {
LogUtil.e(src.getAbsolutePath() + " is not exist.");
return false;
}

long srcFileSize = src.length();
LogUtil.d("copy size(src):" + Long.toString(srcFileSize));

long destFileSize = 0;
if(dest.exists()) {
destFileSize = dest.length();
LogUtil.d("copy size(dest):" + Long.toString(destFileSize));
if(destFileSize > srcFileSize) {
LogUtil.d("destFileSize > srcFileSize,delete dest file and repeat copy.");
dest.delete();
destFileSize = 0;
} else if (destFileSize == srcFileSize) {
LogUtil.d("destFileSize = srcFileSize,copy success.");
if(isdeletesrc) {
LogUtil.d("delete file " + src.getAbsolutePath());
src.delete();
}
return true;
}
}

if (!dest.exists()) {
try {
if (!dest.getParentFile().exists())
dest.getParentFile().mkdirs();
dest.createNewFile();
} catch (IOException e) {
LogUtil.e("create " + dest.getAbsolutePath() + "fail.");
return false;
}
}

try {
RandomAccessFile accessReadFile = new RandomAccessFile(src, "r");
RandomAccessFile accessWriteFile = new RandomAccessFile(dest, "rw");
if(destFileSize > 0) {
accessReadFile.seek(destFileSize);
accessWriteFile.seek(destFileSize);
}

byte[] readByte = new byte[mCopyChunkSize];
int readSize = 0;
while((readSize = accessReadFile.read(readByte)) > 0) {
accessWriteFile.write(readByte, 0, readSize);
}
accessReadFile.close();
accessWriteFile.close();

destFileSize = dest.length();
if(destFileSize == srcFileSize) {
LogUtil.d("-->copy file " + src.getAbsolutePath() + " success.");
if(isdeletesrc) {
LogUtil.d("-->delete file " + src.getAbsolutePath());
src.delete();
}
return true;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

return false;
}


public boolean copyDir(File src, File dest, boolean isdeletesrc) {


if (src.isDirectory()) {
mListFile.clear();
getFileList(src.getAbsolutePath());

ArrayList<String> mDestListFile = new ArrayList<String>();
mDestListFile.clear();


for (String str : mListFile) {
mDestListFile.add(str.replace(src.getAbsolutePath(), dest.getAbsolutePath()));
}


for (int index = 0; index < mListFile.size(); ++index) {
copyFile(new File(mListFile.get(index)), new File(mDestListFile.get(index)), isdeletesrc);
}
return true;
} else {
return copyFile(src, dest, isdeletesrc);
}
}



public static boolean rename(String oldname, String newname) {

File srcFile = new File(oldname);
if(!srcFile.exists()) {
LogUtil.e(oldname + " not exist.");
return false;
}
File destFile = new File(newname);

return srcFile.renameTo(destFile);
}


public void getFileList(String path) {
File root = new File(path);
if (root.isDirectory()) {


File[] list = root.listFiles();
for (File file : list) {
if (file.isDirectory()) {
getFileList(file.getAbsolutePath());
} else {
String fileName = file.getName();
String prefix=fileName.substring(fileName.lastIndexOf(".")+1);
if("ts".equals(prefix)||"mp4".equals(prefix)){
mListFile.add(file.getAbsolutePath());
}
}
}
} else {
mListFile.add(root.getPath());
}
}


public static String getFileExtension(String path) {
if ((path == null) || (path.isEmpty()))
return "";


int index = path.lastIndexOf(".");
if (index < 0)
return "";

return path.substring(index);
}


public static String getFileName(String path, String split) {
int index = path.lastIndexOf(split);
if (index < 0)
return "";


return path.substring(path.lastIndexOf(split) + 1);
}

public static String getFileNameNoExtenxion(String path, String split) {
int index = path.lastIndexOf(split);
if (index < 0)
return "";


return path.substring(path.lastIndexOf(split) + 1, path.lastIndexOf("."));
}


public static boolean deleteDir(File dir) {
if (dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
return dir.delete();
}

public static class FileInfo {
public String mFileParentDir;
public String mAbsolutePath;
public String mFileName;
public String mFileExtension;
public long mFileSize;
}

}



调用方:部分类没上传,筛选部分方法使用

package com.sdmc.media.main;


import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


import javax.swing.JFileChooser;
import javax.swing.JOptionPane;


import com.sdmc.media.util.ChineseToEnglish;
import com.sdmc.media.util.LogUtil;
import com.sdmc.media.util.MyDataBaseUtil;
import com.sdmc.media.util.MyFileUtil;


/**
 *
 * @author __USER__
 */
public class FileDealFrame extends javax.swing.JFrame {


private static final long serialVersionUID = 1L;
/** Creates new form FileDealFrame */
public FileDealFrame() {
initComponents();
}


/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
// GEN-BEGIN:initComponents
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

LogUtil.setDebugOpen(true);


jLabelPath = new javax.swing.JLabel();
jTextFieldPath = new javax.swing.JTextField();
jButton1 = new javax.swing.JButton();
jButton2 = new javax.swing.JButton();
jButton3 = new javax.swing.JButton();
jButton4 = new javax.swing.JButton();


setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("\u89c6\u9891\u540d\u79f0\u4fee\u6539\u5de5\u5177");//视频名称修改工具
setLocationRelativeTo(this);


jLabelPath.setText("\u76ee\u5f55\u8def\u5f84\uff1a");//目录路径:


jTextFieldPath.setToolTipText("\u8bf7\u9009\u62e9\u76ee\u5f55");//请选择目录


jButton1.setText("\u62fc\u97f3\u8f6c\u4e2d\u6587");//拼音转中文
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});


jButton2.setText("\u4e2d\u6587\u8f6c\u62fc\u97f3");// 中文转拼音
jButton2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton2ActionPerformed(evt);
}
});


jButton3.setText("\u9009\u62e9");//选择
jButton3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton3ActionPerformed(evt);
}
});


//jButton4.setText("\u62fc\u97f3\u8f6c\u7b80\u79f0");//拼音转简称
jButton4.setText("\u62fc\u97f3\u8f6c\u7b80\u62fc");//拼音转简称
jButton4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton4ActionPerformed(evt);
}
});


javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout
.createSequentialGroup().addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup().addComponent(jLabelPath)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jTextFieldPath, javax.swing.GroupLayout.PREFERRED_SIZE, 176, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup().addGap(5, 5, 5).addComponent(jButton1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton2)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jButton4)))
.addContainerGap(23, Short.MAX_VALUE)));
layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout
.createSequentialGroup().addGap(44, 44, 44)
.addGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabelPath)
.addComponent(jTextFieldPath, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jButton3))
.addGap(31, 31, 31)
.addGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jButton2)
.addComponent(jButton1)
.addComponent(jButton4))
.addContainerGap(33, Short.MAX_VALUE)));
pack();
}// </editor-fold>
// GEN-END:initComponents


private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
// 拼音转简称
String path = jTextFieldPath.getText();
if (path == null || "".equals(path)) {
JOptionPane.showMessageDialog(this, "目录不能为空", "提示信息", JOptionPane.ERROR_MESSAGE);
return;
}
int i = JOptionPane.showConfirmDialog(this, "是否确认将" + path + "目录下视频名称转成简称?", "提示信息", JOptionPane.OK_CANCEL_OPTION);
if (i == 0) {
try {
pinyinConvertSimple(path);
JOptionPane.showMessageDialog(this, "转换成功", "提示信息", JOptionPane.INFORMATION_MESSAGE);
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "处理失败:" + e.getLocalizedMessage(), "提示信息", JOptionPane.ERROR_MESSAGE);
return;
}
}
}


private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
// 中文转拼音
String path = jTextFieldPath.getText();
if (path == null || "".equals(path)) {
JOptionPane.showMessageDialog(this, "目录不能为空", "提示信息", JOptionPane.ERROR_MESSAGE);
return;
}


int i = JOptionPane.showConfirmDialog(this, "是否确认将" + path + "目录下视频名称转换成拼音?", "提示信息", JOptionPane.OK_CANCEL_OPTION);
if (i == 0) {
try {
chineseConvertPinyin(path);
JOptionPane.showMessageDialog(this, "转换成功", "提示信息", JOptionPane.INFORMATION_MESSAGE);
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "处理失败:" + e.getLocalizedMessage(), "提示信息", JOptionPane.ERROR_MESSAGE);
return;
}
}
}


private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser chooser = new JFileChooser();
chooser.setApproveButtonText("确定");
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); // 设置只选择目录
int returnVal = chooser.showOpenDialog(FileDealFrame.this);
// System.out.println("returnVal="+returnVal);
if (returnVal == JFileChooser.APPROVE_OPTION) {
String path = chooser.getSelectedFile().getPath();
// System.out.println("You chose to open this file: "+
// chooser.getSelectedFile().getPath());
jTextFieldPath.setText(path);
}
}


private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// 拼音转中文
String path = jTextFieldPath.getText();
if (path == null || "".equals(path)) {
JOptionPane.showMessageDialog(this, "目录不能为空", "提示信息", JOptionPane.ERROR_MESSAGE);
return;
}
int i = JOptionPane.showConfirmDialog(this, "是否确认将" + path + "目录下视频名称转成中文?", "提示信息", JOptionPane.OK_CANCEL_OPTION);
if (i == 0) {
try {
pinyinConvertChinese(path);
JOptionPane.showMessageDialog(this, "转换成功", "提示信息", JOptionPane.INFORMATION_MESSAGE);
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "处理失败:" + e.getLocalizedMessage(), "提示信息", JOptionPane.ERROR_MESSAGE);
return;
}
}


}


// 拼音转中文
private void pinyinConvertChinese(String dpath) throws Exception {
ArrayList<String> errorList = new ArrayList<String>();
if (!MyDataBaseUtil.init()) {
LogUtil.e("Mysql init fail.");
errorList.add("拼音转中文:mysql数据库初始化失败...");
return;
}


MyDataBaseUtil dataBaseUtil = new MyDataBaseUtil();
if (!dataBaseUtil.connect("10.10.62.15", "mam", "root", "123456")) {
LogUtil.e("Mysql connnect fail.");
errorList.add("转换简拼:mysql数据库链接失败...");
return;
}


MyFileUtil fileUtil = new MyFileUtil();
fileUtil.getFileList(dpath);
ArrayList<String> list = fileUtil.getFileList();


String fileName = "";
String fileextension = "";
String fileZHName = "";
String fileParentDir = "";
for (String path : list) {


fileName = MyFileUtil.getFileName(path, "\\");
fileextension = MyFileUtil.getFileExtension(path);
fileName = fileName.substring(0, fileName.indexOf(fileextension));
fileParentDir = new File(path).getParent() + "\\";


LogUtil.d("fileParentDir:" + fileParentDir);
LogUtil.d("fileName:" + fileName);


//ResultSet resultSet = dataBaseUtil.selectSqlStr("select v.video_name from ott_video_video v,ott_video_album a where a.provider_id=1 and  a.id =v.album_id and  v.fullspell='" + fileName + "'");
String sql = "select v.video_name,a.album_name from ott_video_video v,ott_video_album a where a.id =v.album_id and v.fullspell='" + fileName + "'";
ResultSet resultSet = dataBaseUtil.selectSqlStr(sql);
if (resultSet == null) {
dataBaseUtil.clear();
LogUtil.e("selectSqlStr fail:" + fileName);
continue;
}


if (!resultSet.next()) {
dataBaseUtil.clear();
LogUtil.e("resultSet.next() fail:" + fileName);
errorList.add(path);
continue;
}
fileZHName = resultSet.getString(1);
if(fileZHName.indexOf("(1080p)") != -1){// 去掉不必要的串
fileZHName = fileZHName.replace("(1080p)", "");
       }
dataBaseUtil.clear();
String targrtPath = fileParentDir + fileZHName + fileextension;
LogUtil.d("源文件路径:" + path + "目标路径:" + targrtPath);
MyFileUtil.rename(path, targrtPath);
}
dataBaseUtil.close();


if (errorList!=null&&errorList.size()>0) {
Writer writer = new OutputStreamWriter(new FileOutputStream(dpath + "\\rename_error.txt"), "UTF-8");
for (String path : errorList) {
writer.write(path + "\n");
writer.flush();
}
writer.close();
}


}


private void pinyinConvertSimple(String dpath) throws Exception {
ArrayList<String> errorList = new ArrayList<String>();
// 拼音转简拼
if (!MyDataBaseUtil.init()) {
LogUtil.e("Mysql init fail.");
errorList.add("转换简拼:mysql数据库初始化失败...");
return;
}


MyDataBaseUtil dataBaseUtil = new MyDataBaseUtil();
if (!dataBaseUtil.connect("10.10.62.15", "mam", "root", "123456")) {
LogUtil.e("Mysql connnect fail.");
errorList.add("转换简拼:mysql数据库链接失败...");
return;
}


MyFileUtil fileUtil = new MyFileUtil();
fileUtil.getFileList(dpath);
ArrayList<String> list = fileUtil.getFileList();
String fileName = "";
String fileextension = "";
String fileZHName = "";
String fileParentDir = "";
for (String path : list) {


fileName = MyFileUtil.getFileName(path, "\\");
fileextension = MyFileUtil.getFileExtension(path);
fileName = fileName.substring(0, fileName.indexOf(fileextension));
fileParentDir = new File(path).getParent() + "\\";


LogUtil.d("fileParentDir:" + fileParentDir);
LogUtil.d("fileName:" + fileName);
String sql = "select v.video_name,a.album_name from ott_video_video v,ott_video_album a where a.id =v.album_id and v.fullspell='" + fileName + "'";
// System.out.println(sql);
ResultSet resultSet = dataBaseUtil.selectSqlStr(sql);
if (resultSet == null) {
dataBaseUtil.clear();
LogUtil.e("selectSqlStr fail:" + fileName);
errorList.add("文件名:"+fileName+",数据库中没有该条数据相关信息");
continue;
}


if (!resultSet.next()) {
dataBaseUtil.clear();
LogUtil.e("resultSet.next() fail:" + fileName);
errorList.add(path);
continue;
}
fileZHName = resultSet.getString(1);// 文件中文名
//String albumName_ZH = resultSet.getString("album_name");// 专辑名
String videoName = "";// 视频名
// 吉林处理
if (fileZHName.indexOf("第") != -1 && fileZHName.indexOf("集") != -1) {
fileZHName = getSeriesSimple(fileZHName);
}
// 获得简拼
videoName = ChineseToEnglish.getPinYinHeadChar(fileZHName);
if(videoName.indexOf("(1080p)") != -1){// 去掉不必要的串
videoName = videoName.replace("(1080p)", "");
       }
dataBaseUtil.clear();
//String targrtPath = fileParentDir + albumName_ZH + "\\" + videoName + fileextension;
String targrtPath = fileParentDir + videoName + fileextension;
LogUtil.d("源文件路径:" + path + "目标路径:" + targrtPath);
MyFileUtil.rename(path, targrtPath);
}
dataBaseUtil.close();

if (errorList!=null&&errorList.size()>0) {
Writer writer = new OutputStreamWriter(new FileOutputStream(dpath + "\\rename_error.txt"), "UTF-8");
for (String path : errorList) {
writer.write(path + "\n");
writer.flush();
}
writer.close();
}

}


@SuppressWarnings("unused")
private void chineseConvertPinyin(String dpath) throws Exception {


MyFileUtil fileUtil = new MyFileUtil();
fileUtil.getFileList(dpath);
ArrayList<String> list = fileUtil.getFileList();


ArrayList<String> errorList = new ArrayList<String>();


String fileName = "";
String fileextension = "";
String fileZHName = "";
String fileParentDir = "";
for (String path : list) {


fileName = MyFileUtil.getFileName(path, "\\");
fileextension = MyFileUtil.getFileExtension(path);
fileName = fileName.substring(0, fileName.indexOf(fileextension));
fileParentDir = new File(path).getParent() + "\\";


LogUtil.d("fileParentDir:" + fileParentDir);
LogUtil.d("fileName:" + fileName);
if (fileName != null) {
Pattern p = Pattern.compile("[\\s*\\《\\》]");
Matcher m = p.matcher(fileName);
fileName = m.replaceAll("");
}
fileZHName = ChineseToEnglish.getPingYin(fileName);


LogUtil.d("******" + fileName + ":" + fileZHName + "******");


LogUtil.d(fileParentDir + fileZHName + fileextension);


LogUtil.d("");
LogUtil.d("path1:" + path);
LogUtil.d("path2:" + fileParentDir + fileZHName + fileextension);
LogUtil.d("");


MyFileUtil.rename(path, fileParentDir + fileZHName + fileextension);
}
}


public static String getSeriesSimple(String js) {
// 小小画家熊小米第1集 小小画家熊小米01
js = js.replaceAll("第1集", "01");
js = js.replaceAll("第2集", "02");
js = js.replaceAll("第3集", "03");
js = js.replaceAll("第4集", "04");
js = js.replaceAll("第5集", "05");
js = js.replaceAll("第6集", "06");
js = js.replaceAll("第7集", "07");
js = js.replaceAll("第8集", "08");
js = js.replaceAll("第9集", "09");


js = js.replaceAll("第", "");
js = js.replaceAll("集", "");


return js;
}
/**
* 读取某个文件夹下的所有文件
*/
public static boolean readfile(String filepath) throws FileNotFoundException, IOException {
try {
File file = new File(filepath);
if (!file.isDirectory()) {
/*
System.out.println("文件");
System.out.println("path=" + file.getPath());
System.out.println("absolutepath=" + file.getAbsolutePath());
System.out.println("name=" + file.getName());
*/
System.out.println(file.getName()+"\t"+file.getAbsolutePath());
} else if (file.isDirectory()) {
String[] filelist = file.list();
for (int i = 0; i < filelist.length; i++) {
File readfile = new File(filepath + "\\" + filelist[i]);
if (!readfile.isDirectory()) {
/*
   System.out.println("path=" + readfile.getPath());
System.out.println("absolutepath=" + readfile.getAbsolutePath());
System.out.println("name=" + readfile.getName());
*/
System.out.println(readfile.getName()+"\t"+readfile.getAbsolutePath());
} else if (readfile.isDirectory()) {
readfile(filepath + "\\" + filelist[i]);
}
}


}


} catch (FileNotFoundException e) {
//System.out.println("readfile()   Exception:" + e.getMessage());
}
return true;
}
/**
* @param args
*            the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new FileDealFrame().setVisible(true);
}
});
}


// GEN-BEGIN:variables
// Variables declaration - do not modify
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JButton jButton3;
private javax.swing.JButton jButton4;
private javax.swing.JLabel jLabelPath;
private javax.swing.JTextField jTextFieldPath;
// End of variables declaration//GEN-END:variables


}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值