- 浏览: 15801 次
- 性别:
- 来自: 杭州
文章分类
最新评论
1.创建文件夹
//import java.io.*;
File myFolderPath = new File(%%1);
try {
if (!myFolderPath.exists())
myFolderPath.mkdir();
}
catch (IOException e) {
System.err.println("新建目录操作出错");
}
2.创建文件
//import java.io.*;
File myFilePath = new File(%%1);
try {
if (!myFilePath.exists())
myFilePath.createNewFile();
FileWriter resultFile = new FileWriter(myFilePath);
PrintWriter myFile = new PrintWriter(resultFile);
myFile.println(%%2);
myFile.flush();
resultFile.close();
}
catch (IOException e) {
System.err.println("新建文件操作出错");
}
3.删除文件
//import java.io.*;
File myDelFile = new File(%%1);
try {
if(myDelFile.delete())
{
%%2
}
}
catch (IOException e) {
System.err.println("删除文件操作出错");
}
4.删除文件夹
/*
import java.io.*;
import java.util.*;
*/
LinkedList<String> folderList = new LinkedList<String>();
folderList.add(%%1);
while (folderList.size() > 0) {
File file = new File((String)folderList.poll());
File[] files = file.listFiles();
ArrayList<File> fileList = new ArrayList<File>();
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
folderList.add(files[i].getPath());
} else {
fileList.add(files[i]);
}
}
for (File f : fileList) {
f.delete();
}
}
folderList = new LinkedList<String>();
folderList.add(%%1);
while (folderList.size() > 0) {
File file = new File((String)folderList.getLast());
if (file.delete())
folderList.removeLast();
else {
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
folderList.add(files[i].getPath());
}
}
}
5.删除一个文件下夹所有的文件夹
/*
import java.io.*;
private static LinkedList<String> folderList=null;
*/
File delfile=new File(%%1);
File[] files=delfile.listFiles();
for(int i=0;i<files.length;i++){
if(files[i].isDirectory()){
if(!files[i].delete()){
folderList = new LinkedList<String>();
folderList.add(files[i]);
while (folderList.size() > 0) {
File file = new File((String)folderList.poll());
File[] files = file.listFiles();
ArrayList<File> fileList = new ArrayList<File>();
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory())
folderList.add(files[i].getPath());
else
fileList.add(files[i]);
}
for (File f : fileList)
f.delete();
}
folderList = new LinkedList<String>();
folderList.add(files[i]);
while (folderList.size() > 0) {
File file = new File((String)folderList.getLast());
if (file.delete())
folderList.removeLast();
else {
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
folderList.add(files[i].getPath());
}
}
}
}
}
}
6.清空文件夹
//import java.io.*;
File delfilefolder=new File(%%1);
if (!delfilefolder.exists() && !delfilefolder.delete()){
LinkedList<String> folderList = new LinkedList<String>();
folderList.add(delfilefolder.getAbsolutePath());
while (folderList.size() > 0) {
File file = new File((String)folderList.poll());
File[] files = file.listFiles();
ArrayList<File> fileList = new ArrayList<File>();
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory())
folderList.add(files[i].getPath());
else
fileList.add(files[i]);
}
for (File f : fileList)
f.delete();
}
folderList = new LinkedList<String>();
folderList.add(delfilefolder.getAbsolutePath());
while (folderList.size() > 0) {
File file = new File((String)folderList.getLast());
if (file.delete())
folderList.removeLast();
else {
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
folderList.add(files[i].getPath());
}
}
}
}
delfilefolder.mkdir();
7.读取文件
//import java.io.*;
7.1.操作系统默认编码
FileReader fr=new FileReader(%%1);
BufferedReader br = new BufferedReader();
String %%2=nul;
try {
while ((%%2 = reader.readLine()) != null) {
%%3
}
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
br.close();
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
7.2.UTF-8编码
FileInputStream fis=new FileInputStream(new File(%%1));
InputStreamReader read = new InputStreamReader(fis,"UTF-8");
BufferedReader reader=new BufferedReader(read);
String %%2=null;
try {
while ((%%2 = reader.readLine()) != null) {
%%3
}
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
br.close();
read.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
7.3.分块读取
FileInputStream fis=new FileInputStream(new File(%%1));
byte[] buffer=new byte[10240];
try {
int byteread;
while ((byteread=fis.read(buffer)) != -1) {
String %%2=new String(buffer);
%%3
}
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
read.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
8.写入文件
//import java.io.*;
8.1.操作系统默认编码
try {
FileWriter fw = new FileWriter(%%1);
fw.write(%%2);
fw.flush();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
8.2.UTF-8编码
try {
OutputStreamWriter out = new OutputStreamWriter(
new FileOutputStream(%%1),"UTF-8");
out.write(sb.toString());
out.flush();
out.close();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e){
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
9.写入随机文件
//import java.io.*;
try {
RandomAcessFile logFile=new RandomAcessFile(%%1,"rw");
long lg=logFile.length();
logFile.seek(%%2);
logFile.writeByte(%%3);
}catch(IOException ioe){
System.out.println("无法写入文件:"+ioe.getMessage());
}
10.读取文件属性
//import java.io.*;
// 文件属性的取得
File af = new File(%%1);
if (af.exists()) {
System.out.println(f.getName() + "的属性如下: 文件长度为:" + f.length());
System.out.println(f.isFile() ? "是文件" : "不是文件");
System.out.println(f.isDirectory() ? "是目录" : "不是目录");
System.out.println(f.canRead() ? "可读取" : "不");
System.out.println(f.canWrite() ? "是隐藏文件" : "");
System.out.println("文件夹的最后修改日期为:" + new Date(f.lastModified()));
} else {
System.out.println(f.getName() + "的属性如下:");
System.out.println(f.isFile() ? "是文件" : "不是文件");
System.out.println(f.isDirectory() ? "是目录" : "不是目录");
System.out.println(f.canRead() ? "可读取" : "不");
System.out.println(f.canWrite() ? "是隐藏文件" : "");
System.out.println("文件的最后修改日期为:" + new Date(f.lastModified()));
}
if(f.canRead()){
%%2
}
if(f.canWrite()){
%%3
}
11.写入属性
//import java.io.*;
File filereadonly=new File(%%1);
try {
boolean %%2=filereadonly.setReadOnly();
}
catch (IOException e) {
System.err.println("拒绝写访问:"+e.printStackTrace());
}
12.枚举一个文件夹中的所有文件
/*
import java.io.*;
import java.util.*;
*/
LinkedList<String> folderList = new LinkedList<String>();
folderList.add(%%1);
while (folderList.size() > 0) {
File file = new File((String)folderList.poll());
File[] files = file.listFiles();
List<File> fileList = new ArrayList<File>();
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory())
folderList.add(files[i].getPath());
else
fileList.add(files[i]);
}
for (File f : fileList) {
%%2=f.getAbsoluteFile();
%%3
}
}
13.复制文件夹
/*
import java.io.*;
import java.util.*;
*/
LinkedList<String> folderList = new LinkedList<String>();
folderList.add(%%1);
LinkedList<String> folderList2 = new LinkedList<String>();
folderList2.add(%%2+ %%1.substring(%%1.lastIndexOf("\\")));
while (folderList.size() > 0) {
(new File(folderList2.peek())).mkdirs(); // 如果文件夹不存在 则建立新文件夹
File folders = new File(folderList.peek());
String[] file = folders.list();
File temp = null;
try {
for (int i = 0; i < file.length; i++) {
if (folderList.peek().endsWith(File.separator))
temp = new File(folderList.peek() + File.separator
+ file[i]);
else
temp = new File(folderList.peek() + File.separator
+ file[i]);
if (temp.isFile()) {
FileInputStream input = new FileInputStream(temp);
FileOutputStream output = new FileOutputStream(new File(
folderList2.peek() ,temp.getName().toString()));
byte[] b = new byte[10240];
int len;
while ((len = input.read(b)) != -1)
output.write(b, 0, len);
output.flush();
output.close();
input.close();
}
else if (temp.isDirectory()) {// 如果是子文件夹
for (File f : temp.listFiles()) {
if (f.isDirectory()) {
folderList.add(f.getPath());
folderList2.add(folderList2.peek()
+ File.separator + f.getName());
}
else if(f.isFile()) {
FileInputStream input = new FileInputStream(f);
FileOutputStream output = new FileOutputStream(folderList2.peek()+File.separator+temp.getName()+File.separator+ f.getName());
byte[] b = new byte[10240];
int len;
while ((len = input.read(b)) != -1)
output.write(b, 0, len);
output.flush();
output.close();
input.close();
}
}
}
}
} catch (IOException e) {
System.err.println("复制整个文件夹内容操作出错");
}
folderList.removeFirst();
folderList2.removeFirst();
}
14.复制一个目录下所有的文件夹到另一个文件夹下
/*
import java.io.*;
import java.util.*;
*/
File copyfolders=new File(%%1);
File[] copyfoldersList=copyfolders.listFiles();
for(int k=0;k<copyfoldersList.length;k++){
if(copyfoldersList[k].isDirectory()){
List<String>folderList=new ArrayList<String>();
folderList.add(copyfoldersList[k].getPath());
List<String>folderList2=new ArrayList<String>();
folderList2.add(%%2+"/"+copyfoldersList[k].getName());
for(int j=0;j<folderList.size();j++){
(new File(folderList2.get(j))).mkdirs(); //如果文件夹不存在 则建立新文件夹
File folders=new File(folderList.get(j));
String[] file=folders.list();
File temp=null;
try {
for (int i = 0; i < file.length; i++) {
if(folderList.get(j).endsWith(File.separator))
temp=new File(folderList.get(j),file[i]);
else
temp=new File(folderList.get(j),file[i]);
FileInputStream input = new FileInputStream(temp);
if(temp.isFile()){
FileOutputStream output = new FileOutputStream(new File(folderList2.get(j) ,temp.getName()).toString()));
byte[] b = new byte[10240];
while ( (int len = input.read(b)) != -1)
output.write(b, 0, len);
output.flush();
output.close();
input.close();
}
else if(temp.isDirectory()){//如果是子文件夹
for (File f : temp.listFiles()) {
if (f.isDirectory()) {
folderList.add(f.getPath());
folderList2.add(folderList2.peek()
+ File.separator + f.getName());
}
else if(f.isFile()) {
FileInputStream input = new FileInputStream(f);
FileOutputStream output = new FileOutputStream(folderList2.peek()+File.separator+temp.getName()+File.separator+ f.getName());
byte[] b = new byte[10240];
int len;
while ((len = input.read(b)) != -1) {
output.write(b, 0, len);
}
output.flush();
output.close();
input.close();
}
}
}
}
}
}
catch (IOException e) {
System.err.println("复制整个文件夹内容操作出错");
}
}
}
}
15.移动文件夹
/*
import java.io.*;
import java.util.*;
*/
LinkedList<String> folderList = new LinkedList<String>();
folderList.add(%%1);
LinkedList<String> folderList2 = new LinkedList<String>();
folderList2.add(%%2 + %%1.substring(%%1.lastIndexOf("\\")));
while (folderList.size() > 0) {
(new File(folderList2.peek())).mkdirs(); // 如果文件夹不存在 则建立新文件夹
File folders = new File(folderList.peek());
String[] file = folders.list();
File temp = null;
try {
for (int i = 0; i < file.length; i++) {
if (folderList.peek().endsWith(File.separator)) {
temp = new File(folderList.peek() , file[i]);
} else {
temp = new File(folderList.peek() ,file[i]);
}
if (temp.isFile()) {
FileInputStream input = new FileInputStream(temp);
FileOutputStream output = new FileOutputStream(
folderList2.peek() + File.separator
+ (temp.getName()).toString());
byte[] b = new byte[10240];
while ((int len = input.read(b)) != -1)
output.write(b, 0, len);
output.flush();
output.close();
input.close();
if (!temp.delete())
//删除单个文件操作出错
}
else if (temp.isDirectory()) {// 如果是子文件夹
for (File f : temp.listFiles()) {
if (f.isDirectory()) {
folderList.add(f.getPath());
folderList2.add(folderList2.peek()
+ File.separator + f.getName());
}
else if (f.isFile()) {
FileInputStream input = new FileInputStream(f);
FileOutputStream output = new FileOutputStream(folderList2.peek()+File.separator+temp.getName()+File.separator+ f.getName());
byte[] b = new byte[10240];
while ((int len = input.read(b)) != -1)
output.write(b, 0, len);
output.flush();
output.close();
input.close();
if (!temp.delete())
//删除单个文件操作出错
}
}
}
}
} catch (IOException e) {
//复制整个文件夹内容操作出错
e.printStackTrace();
}
folderList.removeFirst();
folderList2.removeFirst();
}
File f = new File(%%1);
if (!f.delete()) {
for (File file : f.listFiles()) {
if (file.list().length == 0)
file.delete();
}
}
16.移动一个目录下所有的文件夹到另一个目录下
/*
import java.io.*;
import java.util.*;
*/
File movefolders=new File(%%1);
File[] movefoldersList=movefolders.listFiles();
for(int k=0;k<movefoldersList.length;k++){
if(movefoldersList[k].isDirectory()){
List<String>folderList=new ArrayList<String>();
folderList.add(movefoldersList[k].getPath());
List<String>folderList2=new ArrayList<String>();
folderList2.add(%%2+File.separator+movefoldersList[k].getName());
for(int j=0;j<folderList.size();j++){
(new File(folderList2.get(j))).mkdirs(); //如果文件夹不存在 则建立新文件夹
File folders=new File(folderList.get(j));
String[] file=folders.list();
File temp=null;
try {
for (int i = 0; i < file.length; i++) {
if(folderList.get(j).endsWith(File.separator))
temp=new File(folderList.get(j),file[i]);
else
temp=new File(folderList.get(j),file[i]);
FileInputStream input = new FileInputStream(temp);
if(temp.isFile()){
FileInputStream input = new FileInputStream(temp);
FileOutputStream output = new FileOutputStream(new File(folderList2.get(j),temp.getName().toString()));
byte[] b = new byte[10240];
while ( (int len = input.read(b)) != -1)
output.write(b, 0, len);
output.flush();
output.close();
input.close();
temp.delete();
}
else if(temp.isDirectory()){//如果是子文件夹
for (File f : temp.listFiles()) {
if (f.isDirectory()) {
folderList.add(f.getPath());
folderList2.add(folderList2.peek()
+ File.separator + f.getName());
}
else if (f.isFile()) {
FileInputStream input = new FileInputStream(f);
FileOutputStream output = new FileOutputStream(folderList2.peek()+File.separator+temp.getName()+File.separator+ f.getName());
byte[] b = new byte[10240];
while ((int len = input.read(b)) != -1)
output.write(b, 0, len);
output.flush();
output.close();
input.close();
if (!temp.delete())
//删除单个文件操作出错
}
}
}
}
catch (IOException e) {
//复制整个文件夹内容操作出错
e.printStackTrace();
}
}
movefoldersList[k].delete();
}
}
17.以一个文件夹的框架在另一个目录创建文件夹和空文件
/*
import java.io.*;
import java.util.*;
*/
boolean b=false;//不创建空文件
List<String>folderList=new ArrayList<String>();
folderList.add(%%1);
List<String>folderList2=new ArrayList<String>();
folderList2.add(%%2);
for(int j=0;j<folderList.size();j++){
(new File(folderList2.get(j))).mkdirs(); //如果文件夹不存在 则建立新文件夹
File folders=new File(folderList.get(j));
String[] file=folders.list();
File temp=null;
try {
for (int i = 0; i < file.length; i++) {
if(folderList.get(j).endsWith(File.separator))
temp=new File(folderList.get(j),file[i]);
else
temp=new File(folderList.get(j),file[i]);
if(temp.isFile() && b)
temp.createNewFile();
else if(temp.isDirectory()){//如果是子文件夹
folderList.add(folderList.get(j)+File.separator+file[i]);
folderList2.add(folderList2.get(j)+File.separator+file[i]);
}
}
}
catch (IOException e) {
//复制整个文件夹内容操作出错
e.printStackTrace();
}
}
18.复制文件
//import java.io.*;
File oldfile = new File(%%1);
try {
if (oldfile.exists()) { //文件存在时
FileInputStream inStream = new FileInputStream(oldfile); //读入原文件
FileOutputStream fs = new FileOutputStream(new File(%%2,oldfile.getName()));
byte[] buffer = new byte[10240];
int byteread;
while ( (byteread = inStream.read(buffer)) != -1)
fs.write(buffer, 0, byteread);
inStream.close();
}
}
catch (IOException e) {
//复制单个文件操作出错
e.printStackTrace();
}
19.复制一个目录下所有的文件到另一个目录
//import java.io.*;
File copyfiles=new File(%%1);
File targetfiles = new File(%%2);
if (!targetfiles.exists())
targetfiles.mkdirs();
File[] files=copyfiles.listFiles();
for(int i=0;i<files.length;i++){
if(files[i].isFile()){
try {
InputStream inStream = new FileInputStream(files[i]); //读入原文件
FileOutputStream fs = new FileOutputStream(new File(%%2,files[i].getName()));
byte[] buffer = new byte[10240];
int byteread;
while ( (byteread = inStream.read(buffer)) != -1)
fs.write(buffer, 0, byteread);
inStream.close();
} catch (IOException e) {
//复制单个文件操作出错
e.printStackTrace();
}
}
}
20.提取扩展名
String %%2=%%1.substring(%%1.lastIndexOf('.'));
21.提取文件名
String %%2=%%1.substring(%%1.lastIndexOf("\\")+1);
22.提取文件路径
String %%2=%%1.substring(0,%%1.lastIndexOf("\\"));
23.替换扩展名
//import java.io.*;
File replaceExt=new File(%%1);
replaceExt.renameTo(replaceExt.getName().split(".")[0]+"."+%%2);
24.追加路径
final String path=%%1.endsWith("\\")?%%1:%%1+"\\";
%%3=path+%%2;
25.移动文件
//import java.io.*;
File oldfile = new File(%%1);
try {
if (oldfile.exists()) { //文件存在时
InputStream inStream = new FileInputStream(oldfile); //读入原文件
FileOutputStream fs = new FileOutputStream(new File(%%2,oldfile.getName()));
byte[] buffer = new byte[10240];
int byteread;
while ( (byteread = inStream.read(buffer)) != -1)
fs.write(buffer, 0, byteread);
inStream.close();
oldfile.delete();
}
}
catch (IOException e) {
//复制单个文件操作出错
e.printStackTrace();
}
26.移动一个目录下所有文件到另一个目录
//import java.io.*;
File movefile=new File(%%1);
File[] movefiles=movefile.listFiles();
for(int i=0;i<movefiles.length;i++){
if(movefiles[i].isFile()){
File oldfile = new File(movefiles[i]);
try {
if (oldfile.exists()) { //文件存在时
InputStream inStream = new FileInputStream(oldfile); //读入原文件
FileOutputStream fs = new FileOutputStream(new File(%%2,oldfile.getName()));
byte[] buffer = new byte[10240];
int byteread;
while ( (byteread = inStream.read(buffer)) != -1)
fs.write(buffer, 0, byteread);
inStream.close();
oldfile.delete();
}
}
catch (IOException e) {
//复制单个文件操作出错
e.printStackTrace();
}
}
}
27.指定目录下搜索文件
//import java.io.*;
private static final String filter=%%1; //"*.*"
private static void doSearch(String path){
File file = new File(path);
if(file.exists()) {
if(file.isDirectory()) {
File[] fileArray = file.listFiles();
for(File f:fileArray) {
if(f.isDirectory()) {
doSearch(f.getPath());
} else {
if(f.getName().indexOf(filter) >= 0) {
//f.getPath()
}
}
//f.getPath()
}
//"The numbers of files had been found:" + countFiles
} else {
//"Couldn't open the path!"
}
} else {
System.err.println("目录不存在");
}
}
doSearch(%%1);
28.打开对话框
/*
import java.io.*;
import javax.swing.*;
*/
JFileChooser Jfc = new JFileChooser(); //建立选择档案对话方块盒 Jfc
Jfc.showDialog(null, %%1);
if (Jfc.getSelectedFile() != null) {
File %%2 = Jfc.getSelectedFile();
}
29.文件分割
//import java.io.*;
try {
File f=new File(%%1);
FileInputStream fileInputStream = new FileInputStream(f);
byte[] buffer = new byte[fileInputStream.available()];
FileInputStream.read(buffer);
fileInputStream.close();
String strFileName = f.getName();
FileOutputStream fileOutputStream = new FileOutputStream(new File(%%2+"\\"+ strFileName + "1"));
fileOutputStream.write(buffer,0,buffer.length/2);
fileOutputStream.close();
fileOutputStream = new FileOutputStream(new File(%%2+"\\"+ strFileName + "2"));
fileOutputStream.write(buffer, buffer.length/2, buffer.length-buffer.length/2);
fileOutputStream.close();
} catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
}
catch(IOException e){
e.printStackTrace();
}
30.文件合并
//import java.io.*;
String strFileName = %%1.substring(%%1.LastIndexOf("\\") + 1);
try {
FileInputStream fileInputStream1 = new FileInputStream(new File(%%2 + strFileName + "1"));
FileInputStream fileInputStream2 = new FileInputStream(new File(%%2 + strFileName + "2"));
byte[] buffer = new byte[fileInputStream1.available()+fileInputStream2.available()];
FileInputStream.read(buffer, 0, fileInputStream1.available());
FileInputStream2.read(buffer, fileInputStream1.available(), fileInputStream2.available());
fileInputStream.close();
fileInputStream2.close();
FileOutputStream fileOutputStream = new FileOutputStream(new File(%%2+"\\"+ strFileName));
fileOutputStream.write(buffer,0,buffer.length);
fileOutputStream.close();
}
catch(IOException e){
e.printStackTrace();
}
31.文件简单加密
/*
import java.io.*;
import javax.swing.*;
private static final String CharSet = "0123456789ABCDEF";
*/
JFileChooser jfc = new JFileChooser();
JFileChooser jfc2 = new JFileChooser();
jfc.showDialog(null, "请选择要加密编码的文件");
jfc2.showDialog(null, "请选择要输出的文件名");
if (jfc.getSelectedFile() != null && jfc2.getSelectedFile() != null) {
File oldfile = jfc.getSelectedFile();
FileInputStream inStream = null;
FileWriter fw = null;
try {
if (oldfile.exists()) {
inStream = new FileInputStream(oldfile);
fw = new FileWriter(jfc2.getSelectedFile());
byte[] sRead = new byte[10240];
int byteread;
while ((byteread = inStream.read(sRead)) != -1) {
StringBuilder smi = new StringBuilder(byteread * 2);
int ka = 3, kb = 5, kc = 2, kd = 7, js = 0;
if (byteread % 2 != 0)
js = 1;
for (int i = 0; i < byteread - 1; i += 2) {
char c1 = (char) sRead[i];
char c2 = (char) sRead[i + 1];
int tmp = ka * c1 + kc * c2;
while (tmp < 0)
tmp += 1024;
byte s1 = (byte) (tmp % 1024);
int js1 = (int) s1 >> 4 & 0xf;
smi.append(CharSet.substring(js1, js1 + 1));
int ks1 = s1 & 0xf;
smi.append(CharSet.substring(ks1, ks1 + 1));
tmp = kb * c1 + kd * c2;
while (tmp < 0)
tmp += 1024;
byte s2 = (byte) (tmp % 1024);
int js2 = (int) s2 >> 4 & 0xf;
smi.append(CharSet.substring(js2, js2 + 1));
int ks2 = s2 & 0xf;
smi.append(CharSet.substring(ks2, ks2 + 1));
}
if (js == 1) {
byte s3 = (byte) ((sRead[byteread - 1] - 4) % 1024);
int js3 = (int) s3 >> 4 & 0xf;
smi.append(CharSet.substring(js3, js3 + 1));
int ks3 = (int) s3 & 0xf;
smi.append(CharSet.substring(ks3, ks3 + 1));
}
fw.write(smi.toString());
}
fw.flush();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fw.close();
inStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
32.文件简单解密
/*
import java.io.*;
import javax.swing.*;
private static final String CharSet = "0123456789ABCDEF";
*/
private static int niyuan(int m, int n) {
int a, b, c, d, t, yu = 0, shang, mod;
a = m;
b = n;
mod = a;
c = 0;
d = 1;
while (b < 0)
b += a;
if (a % b == 0 || b % 2 == 0)
return 0;
while (b != 1) {
t = a % b;
shang = a / b;
a = b;
b = t;
yu = c - shang * d;
c = d;
d = yu;
}
if (yu < 0)
yu += mod;
return yu;
}
JFileChooser jfc = new JFileChooser();
JFileChooser jfc2 = new JFileChooser();
jfc.showDialog(null, "请选择要解码解密的文件");
jfc2.showDialog(null, "请选择要输出的文件名");
if (jfc.getSelectedFile() != null && jfc2.getSelectedFile() != null) {
FileOutputStream fw = null;
try {
FileInputStream fis = new FileInputStream(jfc.getSelectedFile());
fw = new FileOutputStream(jfc2
.getSelectedFile());
byte[] buffer = new byte[20480];
int ka = 3, kb = 5, kc = 2, kd = 7, js = 0, tmp;
int aany, ddny;
int r00 = ka * kc * kd;
int r01 = -ka * kb * kc;
int r10 = -kb * kc * kc;
int r11 = ka * kb * kc;
int x00 = ka * ka * kc * kd - ka * kb * kc * kc;
int x11 = ka * kb * kc * kd - kb * kb * kc * kc;
while (x00 % 2 == 0) {
x00 /= 2;
r00 /= 2;
r01 /= 2;
}
while (x11 % 2 == 0) {
x11 /= 2;
r10 /= 2;
r11 /= 2;
}
aany = x00;
ddny = x11;
if (niyuan(1024, aany) != 0 && niyuan(1024, ddny) != 0) {
int kn00 = r00 * niyuan(1024, x00);
int kn01 = r01 * niyuan(1024, x00);
int kn10 = r10 * niyuan(1024, x11);
int kn11 = r11 * niyuan(1024, x11);
ka = kn00;
kb = kn01;
kc = kn10;
kd = kn11;
} else {
JOptionPane.showMessageDialog(null, "无逆矩阵!");
System.exit(0);
}
while (ka < 0)
ka += 1024;
while (kb < 0)
kb += 1024;
while (kc < 0)
kc += 1024;
while (kd < 0)
kd += 1024;
ka %= 1024;
kb %= 1024;
kc %= 1024;
kd %= 1024;
try {
int byteread;
while ((byteread = fis.read(buffer)) != -1) {
int nLen = byteread / 2;
byte[] sming = new byte[nLen];
String chs=new String(buffer,"US-ASCII");
for (int i = 0; i < nLen; i++) {
byte bTmp;
if (byteread < 2)
bTmp = -1;
bTmp = (byte) (CharSet.indexOf(chs.substring(i * 2,i * 2+1)) * 16 + CharSet
.indexOf(chs.substring(i * 2 + 1,i * 2 + 2)));
sming[i] = bTmp;
}
if (nLen % 2 != 0)
js = 1;
for (int i = 0; i < nLen - 1; i += 2) {
char c1 = (char) sming[i];
char c2 = (char) sming[i + 1];
tmp = ka * c1 + kc * c2;
while (tmp < 0)
tmp += 1024;
char s1 = (char) (tmp % 1024);
fw.write(s1);
tmp = kb * c1 + kd * c2;
while (tmp < 0)
tmp += 1024;
char s2 = (char) (tmp % 1024);
fw.write(s2);
}
if (js == 1) {
char c3 = (char) ((sming[nLen - 1] - 4) % 1024);
fw.write(c3);
}
}
fw.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fis.close();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
33.读取ini文件属性
/*
import java.io.*;
import java.util.*;
import java.util.regex.*;
private static HashMap configMap=null;
private static FileReader fileReader = null;
*/
private static boolean readIni() {
if (configMap == null) {
configMap = new HashMap<String, ArrayList>();
String strLine = null;
String currentNode = null;
String previousNode = null;
ArrayList<Properties> vec = new ArrayList<Properties>();
int row = 0;
BufferedReader bufferedReader = new BufferedReader(fileReader);
try {
while ((strLine = bufferedReader.readLine()) != null) {
String oneLine = strLine.trim();
if (oneLine.length() >= 1) {
Pattern p = Pattern.compile("\\[\\s*.*\\s*\\]");
int nodelen = oneLine.split("[;]").length;
String[] strArray1 = new String[4];
if (nodelen == 1) {
oneLine = oneLine.split("[;]")[0].trim();
} else if (nodelen == 2) {
strArray1[3] = oneLine.split("[;]")[1].trim();
oneLine = oneLine.split("[;]")[0].trim();
}
Matcher m = p.matcher(oneLine);
if (m.matches()) {
strArray1[0] = "@Node";
strArray1[1] = oneLine;
strArray1[2] = "";
} else {
int keylen = oneLine.split("=").length;
if (keylen == 1) {
strArray1[0] = "@Key";
strArray1[1] = oneLine.split("=")[0];
strArray1[2] = "";
} else if (keylen == 2) {
strArray1[0] = "@Key";
strArray1[1] = oneLine.split("=")[0];
strArray1[2] = oneLine.split("=")[1];
} else {
strArray1[0] = "@ElementError";
strArray1[1] = "";
strArray1[2] = "";
strArray1[3] = "";
}
}
if (strArray1[0].equals("@Node")) {
previousNode = currentNode;
currentNode = strArray1[1];
if (row > 0) {
configMap.put(previousNode, (ArrayList)vec.clone());
vec.clear();
row = 0;
}
} else if (strArray1[0].equals("@Key") && row == 0) {
Properties ht = new Properties();
ht.setProperty(strArray1[1], strArray1[2]);
vec.add(ht);
row++;
} else if (strArray1[0].equals("@Key") && row > 0) {
Properties ht2 = new Properties();
ht2.put(strArray1[1], strArray1[2]);
vec.add(ht2);
row++;
}
}
}
configMap.put(currentNode, (ArrayList)vec.clone());
} catch (FileNotFoundException e) {
configMap = null;
e.printStackTrace();
return false;
} catch (IOException e) {
configMap = null;
e.printStackTrace();
return false;
}
}
return true;
}
try {
fileReader = new FileReader(%%1); //"Setup.ini"
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
if (readIni()) {
ArrayList<Properties> li = null;
li = (ArrayList<Properties>) configMap.get(%%2); //"[DataSource]"
for (Properties pro : li) {
if(pro.containsKey(%%3))
%%4=pro.getProperty(%%3);
}
}
try {
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
34.合并一个目录下所有的文件
//import java.io.*;
File combinefiles=new File(%%1);
File[] files=combinefiles.listFiles();
FileOutputStream fs;
try {
fs=new FileOutputStream(new File(%%2));
}
catch(IOException e){
e.printStackTrace();
}
for(int i=0;i<files.length;i++){
if(files[i].isFile()){
try {
FileInputStream inStream=new FileInputStream(files[i]);
byte[] buffer = new byte[10240];
int byteread;
while((byteread=inStream.read(buffer))!=-1)
fs.write(buffer,0,byteread);
inStream.close();
}
catch(Exception e){
//复制文件出错
e.printStackTrace();
}
}
}
try {
fs.close();
}
catch(IOException e){
e.printStackTrace();
}
35.写入ini文件属性
/*
import java.io.*;
import java.util.*;
import java.util.regex.*;
private static HashMap configMap=null;
*/
if (readIni()) {
ArrayList<Properties> li = null;
try {
FileWriter fw = new FileWriter(%%1);
li = (ArrayList<Properties>) configMap.get(%%2); //"[DataSource]"
fw.write("%%2\r\n");
for (Properties pro : li) {
if (pro.containsKey(%%3)) //"ip"
fw.write("%%3=" + %%6 + "\r\n");
}
fw.flush();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
36.获得当前路径
String %%1=getClass().getResource("/").getPath();
//String %%1=System.getProperty("user.dir");
37.读取XML数据库
/*
import java.io.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
private static Document document;
private static Element node;
*/
File xml_file = new File(%%1);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder = factory.newDocumentBuilder();
document = builder.parse(xml_file);
} catch (Exception e) {
e.printStackTrace();
}
String subNodeTag = %%2;
Element rootNode = document.getDocumentElement();
//%%2="Product" //%%4="id" //%%6="port"
//%%3="Name" //%%5="001"
NodeList nlist = rootNode.getElementsByTagName(subNodeTag);
int len = nlist.getLength();
for (int i = 0; i < len; i++) {
node = nlist.item(i);
String getNodeAttrValue = null;
NamedNodeMap attrList = node.getAttributes();
for (int j = 0; j < attrList.getLength(); j++) {
if (attrList.item(j).getNodeName().equals(%%4)) {
getNodeAttrValue = attrList.item(j).getNodeValue();
break;
}
}
if (getNodeAttrValue.equals(%%5)) {
nlist = node.getChildNodes();
String %%9=((Element) node).getElementsByTagName(%%3).item(0)
.getFirstChild().getNodeValue();
break;
}
}
38.写入XML数据库
/*
import java.io.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
private Document document;
private Element node;
*/
File xml_file = new File(%%1);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder = factory.newDocumentBuilder();
document = builder.parse(xml_file);
} catch (Exception e) {
e.printStackTrace();
}
String subNodeTag = %%2;
Element rootNode = document.getDocumentElement();
// %%2="Product" //%%4="pid" //%%6="author"
// %%3="Name" //%%5="price"
NodeList nlist = rootNode.getElementsByTagName(subNodeTag);
String ss = null;
int len = nlist.getLength();
for (int i = 0; i < len; i++) {
node = (Element) nlist.item(i);
//node.setAttribute(%%4, "0"+String.valueOf(i)); //ID格式化
String getNodeAttrValue = null;
NamedNodeMap attrList = node.getAttributes();
for (int j = 0; j < attrList.getLength(); j++) {
if (attrList.item(j).getNodeName().equals(%%4)) {
getNodeAttrValue = attrList.item(j).getNodeValue();
break;
}
}
if (getNodeAttrValue.equals("001")) {
nlist = node.getChildNodes();
ss = ((Element) node).getElementsByTagName(%%3).item(0)
.getFirstChild().getNodeValue();
ss = ((Element) node).getElementsByTagName(%%6).item(0)
.getFirstChild().getNodeValue();
ss = ((Element) node).getElementsByTagName(%%5).item(0)
.getFirstChild().getNodeValue();
((Element) node).getElementsByTagName(%%3).item(0)
.getFirstChild().setTextContent(%%7);
((Element) node).getElementsByTagName(%%6).item(0)
.getFirstChild().setTextContent(%%8);
((Element) node).getElementsByTagName(%%5).item(0)
.getFirstChild().setTextContent(%%9);
break;
}
}
if (ss == null) {
node = document.createElement(%%2);
node.setAttribute(%%4, String.valueOf(nlist.getLength() + 1));
node.appendChild(document.createTextNode("\n"));
Element server = document.createElement(%%3);
server.appendChild(document.createTextNode(%%7));
node.appendChild(server);
Element ipNode = document.createElement(%%6);
ipNode.appendChild(document.createTextNode(%%8));
node.appendChild(ipNode);
node.appendChild(document.createTextNode("\n"));
Element port = document.createElement(%%5);
port.appendChild(document.createTextNode(%%9));
node.appendChild(port);
node.appendChild(document.createTextNode("\n"));
rootNode.appendChild(node);
}
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = null;
try {
transformer = tFactory.newTransformer();
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(xml_file);
transformer.transform(source, result);
} catch (IOException e) {
e.printStackTrace();
}
39.ZIP压缩文件
/*
import java.io.*;
import java.util.zip.*;
*/
//创建文件输入流对象
FileInputStream fis=new FileInputStream(%%1);
//创建文件输出流对象
FileOutputStream fos=new FileOutputStream(%%2);
//创建ZIP数据输出流对象
ZipOutputStream zipOut=new ZipOutputStream(fos);
//创建指向压缩原始文件的入口
ZipEntry entry=new ZipEntry(args[0]);
try {
zipOut.putNextEntry(entry);
//向压缩文件中输出数据
int nNumber;
byte[] buffer=new byte[1024];
while((nNumber=fis.read(buffer))!=-1)
zipOut.write(buffer,0,nNumber);
//关闭创建的流对象
zipOut.close();
fos.close();
fis.close();
}
catch(IOException e)
{
e.printStackTrace();
}
40.ZIP解压缩
/*
import java.io.*;
import java.util.zip.*;
*/
//创建文件输入流对象实例
FileInputStream fis=new FileInputStream(%%1);
//创建ZIP压缩格式输入流对象实例
ZipInputStream zipin=new ZipInputStream(fis);
//创建文件输出流对象实例
FileOutputStream fos=new FileOutputStream(%%2);
//获取Entry对象实例
ZipEntry entry=zipin.getNextEntry();
byte[] buffer=new byte[1024];
int nNumber;
try{
while((nNumber=zipin.read(buffer,0,buffer.length))!=-1)
fos.write(buffer,0,nNumber);
//关闭文件流对象
zipin.close();
fos.close();
fis.close();
}
catch(IOException e) {
e.printStackTrace();
}
41.获得应用程序完整路径
String %%1=System.getProperty("user.dir");
42.递归删除目录中的文件
/*
import java.io.*;
import java.util.*;
*/
ArrayList<String> folderList = new ArrayList<String>();
folderList.add(%%1);
for (int j = 0; j < folderList.size(); j++) {
File file = new File(folderList.get(j));
File[] files = file.listFiles();
ArrayList<File> fileList = new ArrayList<File>();
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
folderList.add(files[i].getPath());
} else {
fileList.add(files[i]);
}
}
for (File f : fileList) {
f.delete();
}
}
43.ZIP压缩文件夹
/*
import java.io.*;
import java.util.*;
import java.util.zip.*;
*/
public static String zipFileProcess(ArrayList outputZipFileNameList, String outputZipNameAndPath) {
ArrayList fileNames = new ArrayList();
ArrayList files = new ArrayList();
FileOutputStream fileOut = null;
ZipOutputStream outputStream = null;
FileInputStream fileIn = null;
StringBuffer sb = new StringBuffer(outputZipNameAndPath);
// FileInputStream fileIn =null;
try {
if (outputZipNameAndPath.indexOf(".zip") != -1) {
outputZipNameAndPath = outputZipNameAndPath;
} else {
sb.append(".zip");
outputZipNameAndPath = sb.toString();
}
fileOut = new FileOutputStream(outputZipNameAndPath);
outputStream = new ZipOutputStream(fileOut);
int outputZipFileNameListSize = 0;
if (outputZipFileNameList != null) {
outputZipFileNameListSize = outputZipFileNameList.size();
}
for (int i = 0; i < outputZipFileNameListSize; i++) {
File rootFile = new File(outputZipFileNameList.get(i).toString());
listFile(rootFile, fileNames, files, "");
}
for (int loop = 0; loop < files.size(); loop++) {
fileIn = new FileInputStream((File) files.get(loop));
outputStream.putNextEntry(new ZipEntry((String) fileNames.get(loop)));
byte[] buffer = new byte[1024];
while (fileIn.read(buffer) != -1) {
outputStream.write(buffer);
}
outputStream.closeEntry();
fileIn.close();
}
return outputZipNameAndPath;
} catch (IOException ioe) {
return null;
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
}
}
if (fileIn != null) {
try {
fileIn.close();
} catch (IOException e) {
}
}
}
}
private static void listFile(File parentFile, List nameList, List fileList, String directoryName) {
if (parentFile.isDirectory()) {
File[] files = parentFile.listFiles();
for (int loop = 0; loop < files.length; loop++) {
listFile(files[loop], nameList, fileList, directoryName + parentFile.getName() + "/");
}
} else {
fileList.add(parentFile);
nameList.add(directoryName + parentFile.getName());
}
}
String savePath=%%1;
ArrayList<String> outputZipFileName=new ArrayList<String>();
outputZipFileName.add(%%2);
zipFileProcess(outputZipFileName,savePath);
44.IDEA加密算法
private byte[] bytekey;
public byte[] getKey(String key){
int len1 =key.length();
if (len1>=16) {
key=key.substring(0, 16);
} else {
for (int i=0;i<16-len1;i++){
key=key.concat("0");
}
}
bytekey=key.getBytes();
return bytekey;
}
/**
* 加密String明文输入,String密文输出
* @param strMing
* @return
*/
public String getEncString(String strMing) {
byte[] byteMi = null;
byte[] byteMing = null;
String strMi = "";
try {
return byte2hex(IdeaEncrypt(bytekey,strMing.getBytes(),true) );
}
catch(Exception e){
e.printStackTrace();
}
finally {
byteMing = null;
byteMi = null;
}
return strMi;
}
/**
* 解密 以String密文输入,String明文输出
* @param strMi
* @return
*/
public String getDesString(String strMi) {
byte[] byteMing = null;
byte[] byteMi = null;
String strMing = "";
try {
String tmp= new String(IdeaEncrypt(bytekey,hex2byte(strMi.getBytes()),false ));
int len1=tmp.length();
return tmp.substring(0, len1-6);
}
catch(Exception e) {
e.printStackTrace();
}
finally {
byteMing = null;
byteMi = null;
}
return strMing;
}
private byte[] Encrypt(byte[] bytekey, byte[] inputBytes, boolean flag) {
byte[] encryptCode = new byte[8];
// 分解子密钥
int[] key = get_subkey(flag, bytekey);
// 进行加密操作
encrypt(key, inputBytes, encryptCode);
// 返回加密数据
return encryptCode;
}
private int bytesToInt(byte[] inBytes, int startPos) {
return ((inBytes[startPos] << & 0xff00) +
(inBytes[startPos + 1] & 0xff);
}
private void intToBytes(int inputInt, byte[] outBytes, int startPos) {
outBytes[startPos] = (byte) (inputInt >>>;
outBytes[startPos + 1] = (byte) inputInt;
}
private int x_multiply_y(int x, int y) {
if (x == 0) {
x = 0x10001 - y;
} else if (y == 0) {
x = 0x10001 - x;
} else {
int tmp = x * y;
y = tmp & 0xffff;
x = tmp >>> 16;
x = (y - x) + ((y < x) ? 1 : 0);
}
return x & 0xffff;
}
private void encrypt(int[] key, byte[] inbytes, byte[] outbytes) {
int k = 0;
int a = bytesToInt(inbytes, 0);
int b = bytesToInt(inbytes, 2);
int c = bytesToInt(inbytes, 4);
int d = bytesToInt(inbytes, 6);
for (int i = 0; i < 8; i++) {
a = x_multiply_y(a, key[k++]);
b += key[k++];
b &= 0xffff;
c += key[k++];
c &= 0xffff;
d = x_multiply_y(d, key[k++]);
int tmp1 = b;
int tmp2 = c;
c ^= a;
b ^= d;
c = x_multiply_y(c, key[k++]);
b += c;
b &= 0xffff;
b = x_multiply_y(b, key[k++]);
c += b;
c &= 0xffff;
a ^= b;
d ^= c;
b ^= tmp2;
c ^= tmp1;
}
intToBytes(x_multiply_y(a, key[k++]), outbytes, 0);
intToBytes(c + key[k++], outbytes, 2);
intToBytes(b + key[k++], outbytes, 4);
intToBytes(x_multiply_y(d, key[k]), outbytes, 6);
}
private int[] encrypt_subkey(byte[] byteKey) {
int[] key = new int[52];
if (byteKey.length < 16) {
byte[] tmpkey = new byte[16];
System.arraycopy(byteKey, 0, tmpkey,
tmpkey.length - byteKey.length, byteKey.length);
byteKey = tmpkey;
}
for (int i = 0; i < 8; i++) {
key[i] = bytesToInt(byteKey, i * 2);
}
for (int j = 8; j < 52; j++) {
if ((j & 0x7) < 6) {
key[j] = (((key[j - 7] & 0x7f) << 9) | (key[j - 6] >> 7)) &
0xffff;
} else if ((j & 0x7) == 6) {
key[j] = (((key[j - 7] & 0x7f) << 9) | (key[j - 14] >> 7)) &
0xffff;
} else {
key[j] = (((key[j - 15] & 0x7f) << 9) | (key[j - 14] >> 7)) &
0xffff;
}
}
return key;
}
private int fun_a(int a) {
if (a < 2) {
return a;
}
int b = 1;
int c = 0x10001 / a;
for (int i = 0x10001 % a; i != 1;) {
int d = a / i;
a %= i;
b = (b + (c * d)) & 0xffff;
if (a == 1) {
return b;
}
d = i / a;
i %= a;
c = (c + (b * d)) & 0xffff;
}
return (1 - c) & 0xffff;
}
private int fun_b(int b) {
return (0 - b) & 0xffff;
}
private int[] uncrypt_subkey(int[] key) {
int dec = 52;
int asc = 0;
int[] unkey = new int[52];
int aa = fun_a(key[asc++]);
int bb = fun_b(key[asc++]);
int cc = fun_b(key[asc++]);
int dd = fun_a(key[asc++]);
unkey[--dec] = dd;
unkey[--dec] = cc;
unkey[--dec] = bb;
unkey[--dec] = aa;
for (int k1 = 1; k1 < 8; k1++) {
aa = key[asc++];
bb = key[asc++];
unkey[--dec] = bb;
unkey[--dec] = aa;
aa = fun_a(key[asc++]);
bb = fun_b(key[asc++]);
cc = fun_b(key[asc++]);
dd = fun_a(key[asc++]);
unkey[--dec] = dd;
unkey[--dec] = bb;
unkey[--dec] = cc;
unkey[--dec] = aa;
}
aa = key[asc++];
bb = key[asc++];
unkey[--dec] = bb;
unkey[--dec] = aa;
aa = fun_a(key[asc++]);
bb = fun_b(key[asc++]);
cc = fun_b(key[asc++]);
dd = fun_a(key[asc]);
unkey[--dec] = dd;
unkey[--dec] = cc;
unkey[--dec] = bb;
unkey[--dec] = aa;
return unkey;
}
private int[] get_subkey(boolean flag, byte[] bytekey) {
if (flag) {
return encrypt_subkey(bytekey);
} else {
return uncrypt_subkey(encrypt_subkey(bytekey));
}
}
private byte[] ByteDataFormat(byte[] data, int unit) {
int len = data.length;
int padlen = unit - (len % unit);
int newlen = len + padlen;
byte[] newdata = new byte[newlen];
System.arraycopy(data, 0, newdata, 0, len);
for (int i = len; i < newlen; i++)
newdata[i] = (byte) padlen;
return newdata;
}
public byte[] IdeaEncrypt(byte[] idea_key, byte[] idea_data, boolean flag) {
byte[] format_key = ByteDataFormat(idea_key, 16);
byte[] format_data = ByteDataFormat(idea_data,;
int datalen = format_data.length;
int unitcount = datalen / 8;
byte[] result_data = new byte[datalen];
for (int i = 0; i < unitcount; i++) {
byte[] tmpkey = new byte[16];
byte[] tmpdata = new byte[8];
System.arraycopy(format_key, 0, tmpkey, 0, 16);
System.arraycopy(format_data, i * 8, tmpdata, 0,;
byte[] tmpresult = Encrypt(tmpkey, tmpdata, flag);
System.arraycopy(tmpresult, 0, result_data, i * 8,;
}
return result_data;
}
/**
* 二行制转字符串
* @param b
* @return
*/
public static String byte2hex(byte[] b) { //一个字节的数,
// 转成16进制字符串
String hs = "";
String stmp = "";
for (int n = 0; n < b.length; n++) {
//整数转成十六进制表示
stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
if (stmp.length() == 1)
hs = hs + "0" + stmp;
else
hs = hs + stmp;
}
return hs.toUpperCase(); //转成大写
}
public static byte[] hex2byte(byte[] b) {
if((b.length%2)!=0)
throw new IllegalArgumentException("长度不是偶数");
byte[] b2 = new byte[b.length/2];
for (int n = 0; n < b.length; n+=2) {
String item = new String(b,n,2);
// 两位一组,表示一个字节,把这样表示的16进制字符串,还原成一个进制字节
b2[n/2] = (byte)Integer.parseInt(item,16);
}
return b2;
}
public static void main(String[] args) {
IDEA idea = new IDEA();
idea.getKey("aadd");//生成密匙
String strEnc = idea.getEncString("1234567890");//加密字符串,返回String的密文
System.out.println(strEnc);
String strDes = idea.getDesString(strEnc);//把String 类型的密文解密
System.out.println(strDes);
// String key = "0000000000000000";
// String data = "11111111冯";
// byte[] bytekey = key.getBytes();
// byte[] bytedata = data.getBytes();
//
// IDEA idea = new IDEA();
// byte[] encryptdata = idea.IdeaEncrypt(bytekey, bytedata, true);
// byte[] decryptdata = idea.IdeaEncrypt(bytekey, encryptdata, false);
//
// System.out.println("--------------------------------");
//
// for (int i = 0; i < bytedata.length; i++) {
// System.out.print(" " + bytedata[i] + " ");
// }
//
// System.out.println("");
//
// for (int i = 0; i < encryptdata.length; i++) {
// System.out.print(" " + encryptdata[i] + " ");
// }
//
// System.out.println("");
//
// for (int i = 0; i < decryptdata.length; i++) {
// System.out.print(" " + decryptdata[i] + " ");
// }
}
45.验证Schema
/*
import javax.xml.*;
import javax.xml.transform.stream.*;
import javax.xml.validation.*;
import org.xml.sax.*;
*/
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
StreamSource ss = new StreamSource(%%1); //"mySchema.xsd"
try {
Schema schema = factory.newSchema(ss);
} catch (SAXException e) {
e.printStackTrace();
}
46.Grep
/*
import java.util.regex.*;
import java.io.*;
*/
throws Exception
Pattern pattern = Pattern.compile(%%1); // 第一个参数为需要匹配的字符串
Matcher matcher = pattern.matcher("");
String file = %%2;
BufferedReader br = null;
String line;
try {
br = new BufferedReader (new FileReader (file)); // 打开文件
} catch (IOException e) {
// 没有打开文件,则产生异常
System.err.println ("Cannot read '" + file
+ "': " + e.getMessage());
}
while ((line = br.readLine()) != null) { // 读入一行,直到文件结束
matcher.reset (line); // 匹配字符串
if (matcher.find()) { // 如果有匹配的字符串,则输出
//line
}
}
br.close(); // 关闭文件
47.直接创建多级目录
//import java.io.*;
File f=new File(%%1);
f.mkdirs();
48.批量重命名
//import java.io.*;
File target = new File("%%1");
String[] files = target.list();
File f = null;
String filename = null;
for (String file : files) {
f = new File(target, file);
filename = f.getName();
if (filename.substring(filename.lastIndexOf('.')).equalsIgnoreCase(
"%%2")) {
f.renameTo(new File(target.getAbsolutePath(), filename.replace(
"%%2", "%%3")));
// 这里可以反复使用replace替换,当然也可以使用正则表达式来替换了 ".txt" ".bat"
}
}
49.文本查找替换
//import java.nio.*;
String s1=%%1;
String s2=%%2;
String s3=%%3;
int pos=%%4;
/*变量i和j分别表示主串和模式串中当前字符串的位置,k表示匹配次数*/
int i,j,k=0;
i = pos;
j = 0;
//将s1转化成StringBuffer型进行操作
repStr = new StringBuffer(s1);
while(i<repStr.length()&&j<s2.length())
{
if(repStr.charAt(i) == s2.charAt(j))
{
++i; ++j;
if(j==s2.length())
{
/*j=s2.length()表示字符串匹配成功,匹配次数加1,此外对主串进行字符串替换*/
k = k+1;
repStr.replace(i-j,i,s3);
//将j进行重新赋值开始新的比较
j = 0;
}
}
else {i = i-j+1; j = 0;}
}
return k;
50.文件关联
//import java.io.*;
try {
Runtime.getRuntime().exec(%%1); //"assoc .txt =mynote" "assoc [.ext[=[filetype]]]"
} catch (IOException e) {
e.printStackTrace();
}
51.批量转换编码从GB2312到Unicode
52.设置JDK环境变量
@echo off
IF EXIST %1\bin\java.exe (
rem 如输入正确的 Java2SDK 安装目录,开始设置环境变量
@setx JAVA_HOME %1
@setx path %path%;%JAVA_HOME%\bin
@setx classpath %classpath%;.
@setx classpath %classpath%;%JAVA_HOME%\lib\tools.jar
@setx classpath %classpath%;%JAVA_HOME%\lib\dt.jar
@setx classpath %classpath%;%JAVA_HOME%\jre\lib\rt.jar
@echo on
@echo Java 2 SDK 环境参数设置完毕,正常退出。
) ELSE (
IF "%1"=="" (
rem 如没有提供安装目录,提示之后退出
@echo on
@echo 没有提供 Java2SDK 的安装目录,不做任何设置,现在退出环境变量设置。
) ELSE (
rem 如果提供非空的安装目录但没有bin\java.exe,则指定的目录为错误的目录
@echo on
@echo 非法的 Java2SDK 的安装目录,不做任何设置,现在退出环境变量设置。
)
)
//http://sourceforge.net/projects/jregistrykey/
//import ca.beq.util.win32.registry.*;
//import java.util.*;
1.打开键
RegistryKey r = new RegistryKey(RootKey.HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders");
2.添加键
RegistryKey r = new RegistryKey(RootKey.HKEY_CURRENT_USER, "Software\\BEQ Technologies");
r.create();
9.写入字符串值
RegistryKey r = new RegistryKey(RootKey.HKEY_CURRENT_USER, "Software\\BEQ Technologies");
RegistryValue v = new RegistryValue("myVal", ValueType.REG_SZ, "data");
r.setValue(v);
6.获取DWORD值
RegistryKey r = new RegistryKey(RootKey.HKEY_CURRENT_USER, "Software\\BEQ Technologies");
if(r.hasValue("myValue")) {
RegistryValue v = r.getValue("myValue");
v.setType(ValueType.REG_DWORD);
} // if
53.批量转换编码从Unicode到GB2312
54.删除空文件夹
//import java.io.*;
File f=new File(%%1);
if (isFolerNull(f)) {
for (File file :f.listFiles()) {
if (file.list().length == 0)
file.delete();
}
}
55.GB2312文件转UTF-8格式
//import java.io.*;
public class CharsetConvertor {
public static void main(String[] args) {
String str = "This is a test for *中网!@#$。,?";
try {
File f = new File("D:/test.txt");
FileOutputStream fio = new FileOutputStream(f);
String s = gbToUtf8(str);
fio.write(s.getBytes("UTF-8"));
fio.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
public static String gbToUtf8(String str) throws UnsupportedEncodingException {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < str.length(); i++) {
String s = str.substring(i, i + 1);
if (s.charAt(0) > 0x80) {
byte[] bytes = s.getBytes("Unicode");
String binaryStr = "";
for (int j = 2; j < bytes.length; j += 2) {
// the first byte
String hexStr = getHexString(bytes[j + 1]);
String binStr = getBinaryString(Integer.valueOf(hexStr, 16));
binaryStr += binStr;
// the second byte
hexStr = getHexString(bytes[j]);
binStr = getBinaryString(Integer.valueOf(hexStr, 16));
binaryStr += binStr;
}
// convert unicode to utf-8
String s1 = "1110" + binaryStr.substring(0, 4);
String s2 = "10" + binaryStr.substring(4, 10);
String s3 = "10" + binaryStr.substring(10, 16);
byte[] bs = new byte[3];
bs[0] = Integer.valueOf(s1, 2).byteValue();
bs[1] = Integer.valueOf(s2, 2).byteValue();
bs[2] = Integer.valueOf(s3, 2).byteValue();
String ss = new String(bs, "UTF-8");
sb.append(ss);
} else {
sb.append(s);
}
}
return sb.toString();
}
private static String getHexString(byte b) {
String hexStr = Integer.toHexString(b);
int m = hexStr.length();
if (m < 2) {
hexStr = "0" + hexStr;
} else {
hexStr = hexStr.substring(m - 2);
}
return hexStr;
}
private static String getBinaryString(int i) {
String binaryStr = Integer.toBinaryString(i);
int length = binaryStr.length();
for (int l = 0; l < 8 - length; l++) {
binaryStr = "0" + binaryStr;
}
return binaryStr;
}
}
56.UTF-8文件转GB2312格式
private String utf8Togb2312(String str){
StringBuffer sb = new StringBuffer();
for(int i=0; i<str.length(); i++) {
char c = str.charAt(i);
switch (c) {
case '+':
sb.append(' ');
break;
case '%':
try {
sb.append((char)Integer.parseInt(
str.substring(i+1,i+3),16));
}
catch (NumberFormatException e) {
throw new IllegalArgumentException();
}
i += 2;
break;
default:
sb.append(c);
break;
}
}
// Undo conversion to external encoding
String result = sb.toString();
String res=null;
try{
byte[] inputBytes = result.getBytes("8859_1");
res= new String(inputBytes,"UTF-8");
}
catch(Exception e){}
return res;
}
57.获取文件路径的父路径
String %%2=%%1.substring(0,%%1.lastIndexOf("\\"));
58.Unicode文件转UTF-8格式
try {
// Convert from Unicode to UTF-8
String string = "abc\u5639\u563b";
byte[] utf8 = string.getBytes("UTF-8");
// Convert from UTF-8 to Unicode
string = new String(utf8, "UTF-8");
} catch (UnsupportedEncodingException e) {
}
/**
* unicode 转换成 utf-8
* @author fanhui
* 2007-3-15
* @param theString
* @return
*/
public static String unicodeToUtf8(String theString) {
char aChar;
int len = theString.length();
StringBuffer outBuffer = new StringBuffer(len);
for (int x = 0; x < len;) {
aChar = theString.charAt(x++);
if (aChar == '\\') {
aChar = theString.charAt(x++);
if (aChar == 'u') {
// Read the xxxx
int value = 0;
for (int i = 0; i < 4; i++) {
aChar = theString.charAt(x++);
switch (aChar) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
value = (value << 4) + aChar - '0';
break;
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
value = (value << 4) + 10 + aChar - 'a';
break;
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
value = (value << 4) + 10 + aChar - 'A';
break;
default:
throw new IllegalArgumentException(
"Malformed \\uxxxx encoding.");
}
}
outBuffer.append((char) value);
} else {
if (aChar == 't')
aChar = '\t';
else if (aChar == 'r')
aChar = '\r';
else if (aChar == 'n')
aChar = '\n';
else if (aChar == 'f')
aChar = '\f';
outBuffer.append(aChar);
}
} else
outBuffer.append(aChar);
}
return outBuffer.toString();
}
59.CRC循环冗余校验
/*
import java.nio.*;
import java.util.zip.*;
*/
try {
FileInputStream in = new FileInputStream(%%1);
FileChannel channel = in.getChannel();
CRC32 crc = new CRC32();
int length = (int)channel.size();
MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, length);
for(int i = 0;i<length;i++)
{
int c = buffer.get(i);
crc.update(c);
}
System.out.println("crc校验和:"+(Long.toHexString(crc.getValue())).toUpperCase());
} catch (Exception e) {
e.printStackTrace();
}
60.判断是否为空文件
//import java.io.*;
FileReader fr=new FileReader(%%1);
if(fr.read()==1)
//空白文件
61.终止程序
Runtime.exec("taskkill /F /IM %%1.exe");
62.定时关机
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.util.*;
import javax.swing.*;
public class ClockFrame extends JFrame {
private JComboBox hourBox, minuteBox, secondBox;
private int hour, minute, second, totalSeconds, currentSeconds;
private long argue;
private GregorianCalendar calendar;
private boolean change = true;
private static final int WIDTH = 200;
private static final int HEIGHT = 150;
public ClockFrame() {
setTitle("关机定时");
setSize(200, 150);
Container contentPanel = getContentPane();
JPanel timePanel = new JPanel();
timePanel.setLayout(new GridLayout(4, 2));
JLabel minuteLable = new JLabel("设置分钟");
timePanel.add(minuteLable);
minuteBox = new JComboBox();
timePanel.add(minuteBox);
for (int i = 0; i < 60; i++) {
minuteBox.addItem(i);
}
minuteBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
minute = ((Integer) minuteBox.getSelectedItem()).intValue();
}
});
JLabel secondLable = new JLabel("设置秒钟");
timePanel.add(secondLable);
secondBox = new JComboBox();
timePanel.add(secondBox);
for (int i = 0; i < 60; i++) {
secondBox.addItem(i);
}
secondBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
second = ((Integer) secondBox.getSelectedItem()).intValue();
}
});
contentPanel.add(timePanel, BorderLayout.CENTER);
JButton check = new JButton("确定");
contentPanel.add(check, BorderLayout.SOUTH);
check.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
JButton check=(JButton) evt.getSource();
if (check.getText().equals("确定")) {
calendar = new GregorianCalendar();
int currentSeconds = calendar.get(Calendar.HOUR_OF_DAY)
* 3600 + calendar.get(Calendar.MINUTE) * 60
+ calendar.get(Calendar.SECOND);
totalSeconds = hour * 3600 + minute * 60 + second;
if (totalSeconds - currentSeconds >= 0) {
argue = (totalSeconds - currentSeconds) * 1000;
JOptionPane.showMessageDialog(ClockFrame.this,
"您设置的时间为 " + hour + ":" + minute + ":" + second
+ "\n程序将在后台运行,并在此时自动关闭计算机!", "设置成功",
JOptionPane.INFORMATION_MESSAGE);
hideFrame();
}
try {
// Thread.sleep(argue);//这句没用
Runtime.getRuntime().exec(
"shutdown.exe -s -c \"我要关机了噢!不好意思!\" -t "
+ totalSeconds);
check.setText("取消");
} catch (Exception e) {
e.printStackTrace();
}
}else{
try {
Runtime.getRuntime().exec("shutdown.exe -a");
check.setText("确定");
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
}
private void hideFrame() {
this.setVisible(false);
}
public static void main(String[] args) {
JFrame frame = new ClockFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationByPlatform(true);
frame.show();
}
}
63.显示进程列表
//import java.io.*;
BufferedReader br=null;
try {
Process proc=Runtime.getRuntime().exec("tasklist");
br=new BufferedReader(new InputStreamReader(proc.getInputStream()));
@SuppressWarnings("unused")
String line=null;
while((line=br.readLine())!=null){
//br.readLine()
}
} catch (IOException e) {
e.printStackTrace();
}finally{
if(br!=null){
try {
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
64.遍历文件夹列出文件大小
65.目录下所有文件移动到整合操作
/*
import java.io.*;
import java.util.*;
import javax.swing.*;
*/
JFileChooser Jfc = new JFileChooser("请选择源路径"); // 建立选择档案对话方块盒 Jfc
Jfc.showDialog(null, %%1);
if (!Jfc.getSelectedFile() != null) {
return;
}
String %%1 = Jfc.getSelectedFile().getParent();
Jfc = new JFileChooser("请选择目标路径"); // 建立选择档案对话方块盒 Jfc
Jfc.showDialog(null, %%1);
if (!Jfc.getSelectedFile() != null) {
return;
}
String %%2 = Jfc.getSelectedFile().getParent();
66.对目标压缩文件解压缩到指定文件夹
/*
import java.io.*;
import java.util.zip.*;
*/
String zipFileName=%%1;
String extPlace=%%2;
File myFolderPath = new File(extPlace);
try {
if (!myFolderPath.exists()) {
myFolderPath.mkdir();
}
} catch (Exception e) {
//新建目录操作出错
e.printStackTrace();
return;
}
try {
ZipInputStream in = new ZipInputStream(new FileInputStream(
zipFileName));
ZipEntry entry = null;
while ((entry = in.getNextEntry()) != null) {
String entryName = entry.getName();
File file = new File(extPlace , entryName);
if (entry.isDirectory()) {
file.mkdirs();
} else {
FileOutputStream os = new FileOutputStream(file);
// Transfer bytes from the ZIP file to the output
// file
byte[] buf = new byte[10240];
int len;
while ((len = in.read(buf)) > 0) {
os.write(buf, 0, len);
}
os.close();
in.closeEntry();
}
}
} catch (IOException e) {
e.printStackTrace();
}
67.创建目录副本整合操作
/*
import java.io.*;
import java.util.*;
import javax.swing.*;
*/
JFileChooser Jfc = new JFileChooser("请选择源路径"); // 建立选择档案对话方块盒 Jfc
Jfc.showDialog(null, %%1);
if (!Jfc.getSelectedFile() != null) {
return;
}
String %%1 = Jfc.getSelectedFile().getParent();
Jfc = new JFileChooser("请选择目标路径"); // 建立选择档案对话方块盒 Jfc
Jfc.showDialog(null, %%1);
if (!Jfc.getSelectedFile() != null) {
return;
}
String %%2 = Jfc.getSelectedFile().getParent();
68.打开网页
//import java.io.*;
try{
String command = "C:\\Program Files\\Internet Explorer\\Iexplore.exe "+%%1;
Runtime.getRuntime().exec(command);
} catch (IOException ex) {
ex.printStackTrace();
}
69.删除空文件夹整合操作
/*
import java.io.*;
import java.util.*;
import javax.swing.*;
*/
70.获取磁盘所有分区,把结果放在数组drives中
String root; //root代表盘符路径
for(i=0;i<20;i++) //0-20代表最大的盘符数
{
root.Format("%c:\\",allfenqu[i]);
if(GetDriveType(root)==5)
allfenqu[i]='\0';
}
但我用这样的代码时结果却无法去掉光驱盘符,allfenqu[]中还是会包含光驱盘符:
String root;
for(i=0;i<20;i++)
{
root=allfenqu[i]+":\\";
if(GetDriveType(root)==5)
allfenqu[i]='\0';
}
71.激活一个程序或程序关联的文件
//import java.io.*;
try {
Runtime.getRuntime().exec(%%1);
} catch (IOException e) {
e.printStackTrace();
}
72.MP3播放
//必须下载 jmf包
//import javax.media.bean.playerbean.MediaPlayer; //必须下载 jmf 媒体播放包
MediaPlayer player;
player = new MediaPlayer();
setLayout(new FlowLayout());
try{
player.setMediaLocation("file:/F:\\音乐\\mp3\\黑白配.mp3");// <<file:/>>不能删除 音频文件路径
} catch (Exception e) {
System.err.println("文件不存在");
}
player.start();
player.stop();
73.WAV播放
/*
import javax.sound.sampled.*;
import java.io.*;
*/
private AudioFormat format;
private byte[] samples;
private String filename;
try {
// open the audio input stream
AudioInputStream stream =AudioSystem.getAudioInputStream(new File(filename));
format = stream.getFormat();
// get the audio samples
samples = getSamples(stream);
}
catch (UnsupportedAudioFileException ex) {
ex.printStackTrace();
}
catch (IOException ex) {
ex.printStackTrace();
}
private byte[] getSamples(AudioInputStream audioStream) {
// get the number of bytes to read
int length = (int)(audioStream.getFrameLength() * format.getFrameSize());
// read the entire stream
byte[] samples = new byte[length];
DataInputStream is = new DataInputStream(audioStream);
try {
is.readFully(samples);
}
catch (IOException ex) {
ex.printStackTrace();
}
// return the samples
return samples;
}
public void play(InputStream source) {
// use a short, 100ms (1/10th sec) buffer for real-time
// change to the sound stream
int bufferSize = format.getFrameSize() *
Math.round(format.getSampleRate() / 10);
byte[] buffer = new byte[bufferSize];
// create a line to play to
SourceDataLine line;
try {
DataLine.Info info =
new DataLine.Info(SourceDataLine.class, format);
line = (SourceDataLine)AudioSystem.getLine(info);
line.open(format, bufferSize);
}
catch (LineUnavailableException ex) {
ex.printStackTrace();
return;
}
// start the line
line.start();
// copy data to the line
try {
int numBytesRead = 0;
while (numBytesRead != -1) {
numBytesRead =
source.read(buffer, 0, buffer.length);
if (numBytesRead != -1) {
line.write(buffer, 0, numBytesRead);
}
}
}
catch (IOException ex) {
ex.printStackTrace();
}
// wait until all data is played, then close the line
line.drain();
line.close();
}
throws Exception
String filename=%%1;
InputStream stream =new ByteArrayInputStream(sound.getSamples());
// play the sound
sound.play(stream);
74.写图像到剪切板
/*
import java.awt.*;
import java.awt.datatransfer.*;
import java.io.*;
private final Image image;
*/
Transferable trans = new Transferable() {
public DataFlavor[] getTransferDataFlavors() {
return new DataFlavor[] { DataFlavor.imageFlavor };
}
public boolean isDataFlavorSupported(DataFlavor flavor) {
return DataFlavor.imageFlavor.equals(flavor);
}
public Object getTransferData(DataFlavor flavor)
throws UnsupportedFlavorException, IOException {
if (isDataFlavorSupported(flavor))
return image;
throw new UnsupportedFlavorException(flavor);
}
};
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(trans,
null);
75.从剪贴板复制图像到窗体
76.删除文件夹下的所有文件且不删除文件夹下的文件夹
/*
import java.io.*;
import java.util.*;
*/
LinkedList<String> folderList = new LinkedList<String>();
folderList.add(%%1);
while (folderList.size() > 0) {
File file = new File((String)folderList.poll());
File[] files = file.listFiles();
ArrayList<File> fileList = new ArrayList<File>();
for (int i = 0; i < files.length; i++) {
if (file
//import java.io.*;
File myFolderPath = new File(%%1);
try {
if (!myFolderPath.exists())
myFolderPath.mkdir();
}
catch (IOException e) {
System.err.println("新建目录操作出错");
}
2.创建文件
//import java.io.*;
File myFilePath = new File(%%1);
try {
if (!myFilePath.exists())
myFilePath.createNewFile();
FileWriter resultFile = new FileWriter(myFilePath);
PrintWriter myFile = new PrintWriter(resultFile);
myFile.println(%%2);
myFile.flush();
resultFile.close();
}
catch (IOException e) {
System.err.println("新建文件操作出错");
}
3.删除文件
//import java.io.*;
File myDelFile = new File(%%1);
try {
if(myDelFile.delete())
{
%%2
}
}
catch (IOException e) {
System.err.println("删除文件操作出错");
}
4.删除文件夹
/*
import java.io.*;
import java.util.*;
*/
LinkedList<String> folderList = new LinkedList<String>();
folderList.add(%%1);
while (folderList.size() > 0) {
File file = new File((String)folderList.poll());
File[] files = file.listFiles();
ArrayList<File> fileList = new ArrayList<File>();
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
folderList.add(files[i].getPath());
} else {
fileList.add(files[i]);
}
}
for (File f : fileList) {
f.delete();
}
}
folderList = new LinkedList<String>();
folderList.add(%%1);
while (folderList.size() > 0) {
File file = new File((String)folderList.getLast());
if (file.delete())
folderList.removeLast();
else {
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
folderList.add(files[i].getPath());
}
}
}
5.删除一个文件下夹所有的文件夹
/*
import java.io.*;
private static LinkedList<String> folderList=null;
*/
File delfile=new File(%%1);
File[] files=delfile.listFiles();
for(int i=0;i<files.length;i++){
if(files[i].isDirectory()){
if(!files[i].delete()){
folderList = new LinkedList<String>();
folderList.add(files[i]);
while (folderList.size() > 0) {
File file = new File((String)folderList.poll());
File[] files = file.listFiles();
ArrayList<File> fileList = new ArrayList<File>();
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory())
folderList.add(files[i].getPath());
else
fileList.add(files[i]);
}
for (File f : fileList)
f.delete();
}
folderList = new LinkedList<String>();
folderList.add(files[i]);
while (folderList.size() > 0) {
File file = new File((String)folderList.getLast());
if (file.delete())
folderList.removeLast();
else {
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
folderList.add(files[i].getPath());
}
}
}
}
}
}
6.清空文件夹
//import java.io.*;
File delfilefolder=new File(%%1);
if (!delfilefolder.exists() && !delfilefolder.delete()){
LinkedList<String> folderList = new LinkedList<String>();
folderList.add(delfilefolder.getAbsolutePath());
while (folderList.size() > 0) {
File file = new File((String)folderList.poll());
File[] files = file.listFiles();
ArrayList<File> fileList = new ArrayList<File>();
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory())
folderList.add(files[i].getPath());
else
fileList.add(files[i]);
}
for (File f : fileList)
f.delete();
}
folderList = new LinkedList<String>();
folderList.add(delfilefolder.getAbsolutePath());
while (folderList.size() > 0) {
File file = new File((String)folderList.getLast());
if (file.delete())
folderList.removeLast();
else {
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
folderList.add(files[i].getPath());
}
}
}
}
delfilefolder.mkdir();
7.读取文件
//import java.io.*;
7.1.操作系统默认编码
FileReader fr=new FileReader(%%1);
BufferedReader br = new BufferedReader();
String %%2=nul;
try {
while ((%%2 = reader.readLine()) != null) {
%%3
}
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
br.close();
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
7.2.UTF-8编码
FileInputStream fis=new FileInputStream(new File(%%1));
InputStreamReader read = new InputStreamReader(fis,"UTF-8");
BufferedReader reader=new BufferedReader(read);
String %%2=null;
try {
while ((%%2 = reader.readLine()) != null) {
%%3
}
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
br.close();
read.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
7.3.分块读取
FileInputStream fis=new FileInputStream(new File(%%1));
byte[] buffer=new byte[10240];
try {
int byteread;
while ((byteread=fis.read(buffer)) != -1) {
String %%2=new String(buffer);
%%3
}
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
read.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
8.写入文件
//import java.io.*;
8.1.操作系统默认编码
try {
FileWriter fw = new FileWriter(%%1);
fw.write(%%2);
fw.flush();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
8.2.UTF-8编码
try {
OutputStreamWriter out = new OutputStreamWriter(
new FileOutputStream(%%1),"UTF-8");
out.write(sb.toString());
out.flush();
out.close();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (FileNotFoundException e){
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
9.写入随机文件
//import java.io.*;
try {
RandomAcessFile logFile=new RandomAcessFile(%%1,"rw");
long lg=logFile.length();
logFile.seek(%%2);
logFile.writeByte(%%3);
}catch(IOException ioe){
System.out.println("无法写入文件:"+ioe.getMessage());
}
10.读取文件属性
//import java.io.*;
// 文件属性的取得
File af = new File(%%1);
if (af.exists()) {
System.out.println(f.getName() + "的属性如下: 文件长度为:" + f.length());
System.out.println(f.isFile() ? "是文件" : "不是文件");
System.out.println(f.isDirectory() ? "是目录" : "不是目录");
System.out.println(f.canRead() ? "可读取" : "不");
System.out.println(f.canWrite() ? "是隐藏文件" : "");
System.out.println("文件夹的最后修改日期为:" + new Date(f.lastModified()));
} else {
System.out.println(f.getName() + "的属性如下:");
System.out.println(f.isFile() ? "是文件" : "不是文件");
System.out.println(f.isDirectory() ? "是目录" : "不是目录");
System.out.println(f.canRead() ? "可读取" : "不");
System.out.println(f.canWrite() ? "是隐藏文件" : "");
System.out.println("文件的最后修改日期为:" + new Date(f.lastModified()));
}
if(f.canRead()){
%%2
}
if(f.canWrite()){
%%3
}
11.写入属性
//import java.io.*;
File filereadonly=new File(%%1);
try {
boolean %%2=filereadonly.setReadOnly();
}
catch (IOException e) {
System.err.println("拒绝写访问:"+e.printStackTrace());
}
12.枚举一个文件夹中的所有文件
/*
import java.io.*;
import java.util.*;
*/
LinkedList<String> folderList = new LinkedList<String>();
folderList.add(%%1);
while (folderList.size() > 0) {
File file = new File((String)folderList.poll());
File[] files = file.listFiles();
List<File> fileList = new ArrayList<File>();
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory())
folderList.add(files[i].getPath());
else
fileList.add(files[i]);
}
for (File f : fileList) {
%%2=f.getAbsoluteFile();
%%3
}
}
13.复制文件夹
/*
import java.io.*;
import java.util.*;
*/
LinkedList<String> folderList = new LinkedList<String>();
folderList.add(%%1);
LinkedList<String> folderList2 = new LinkedList<String>();
folderList2.add(%%2+ %%1.substring(%%1.lastIndexOf("\\")));
while (folderList.size() > 0) {
(new File(folderList2.peek())).mkdirs(); // 如果文件夹不存在 则建立新文件夹
File folders = new File(folderList.peek());
String[] file = folders.list();
File temp = null;
try {
for (int i = 0; i < file.length; i++) {
if (folderList.peek().endsWith(File.separator))
temp = new File(folderList.peek() + File.separator
+ file[i]);
else
temp = new File(folderList.peek() + File.separator
+ file[i]);
if (temp.isFile()) {
FileInputStream input = new FileInputStream(temp);
FileOutputStream output = new FileOutputStream(new File(
folderList2.peek() ,temp.getName().toString()));
byte[] b = new byte[10240];
int len;
while ((len = input.read(b)) != -1)
output.write(b, 0, len);
output.flush();
output.close();
input.close();
}
else if (temp.isDirectory()) {// 如果是子文件夹
for (File f : temp.listFiles()) {
if (f.isDirectory()) {
folderList.add(f.getPath());
folderList2.add(folderList2.peek()
+ File.separator + f.getName());
}
else if(f.isFile()) {
FileInputStream input = new FileInputStream(f);
FileOutputStream output = new FileOutputStream(folderList2.peek()+File.separator+temp.getName()+File.separator+ f.getName());
byte[] b = new byte[10240];
int len;
while ((len = input.read(b)) != -1)
output.write(b, 0, len);
output.flush();
output.close();
input.close();
}
}
}
}
} catch (IOException e) {
System.err.println("复制整个文件夹内容操作出错");
}
folderList.removeFirst();
folderList2.removeFirst();
}
14.复制一个目录下所有的文件夹到另一个文件夹下
/*
import java.io.*;
import java.util.*;
*/
File copyfolders=new File(%%1);
File[] copyfoldersList=copyfolders.listFiles();
for(int k=0;k<copyfoldersList.length;k++){
if(copyfoldersList[k].isDirectory()){
List<String>folderList=new ArrayList<String>();
folderList.add(copyfoldersList[k].getPath());
List<String>folderList2=new ArrayList<String>();
folderList2.add(%%2+"/"+copyfoldersList[k].getName());
for(int j=0;j<folderList.size();j++){
(new File(folderList2.get(j))).mkdirs(); //如果文件夹不存在 则建立新文件夹
File folders=new File(folderList.get(j));
String[] file=folders.list();
File temp=null;
try {
for (int i = 0; i < file.length; i++) {
if(folderList.get(j).endsWith(File.separator))
temp=new File(folderList.get(j),file[i]);
else
temp=new File(folderList.get(j),file[i]);
FileInputStream input = new FileInputStream(temp);
if(temp.isFile()){
FileOutputStream output = new FileOutputStream(new File(folderList2.get(j) ,temp.getName()).toString()));
byte[] b = new byte[10240];
while ( (int len = input.read(b)) != -1)
output.write(b, 0, len);
output.flush();
output.close();
input.close();
}
else if(temp.isDirectory()){//如果是子文件夹
for (File f : temp.listFiles()) {
if (f.isDirectory()) {
folderList.add(f.getPath());
folderList2.add(folderList2.peek()
+ File.separator + f.getName());
}
else if(f.isFile()) {
FileInputStream input = new FileInputStream(f);
FileOutputStream output = new FileOutputStream(folderList2.peek()+File.separator+temp.getName()+File.separator+ f.getName());
byte[] b = new byte[10240];
int len;
while ((len = input.read(b)) != -1) {
output.write(b, 0, len);
}
output.flush();
output.close();
input.close();
}
}
}
}
}
}
catch (IOException e) {
System.err.println("复制整个文件夹内容操作出错");
}
}
}
}
15.移动文件夹
/*
import java.io.*;
import java.util.*;
*/
LinkedList<String> folderList = new LinkedList<String>();
folderList.add(%%1);
LinkedList<String> folderList2 = new LinkedList<String>();
folderList2.add(%%2 + %%1.substring(%%1.lastIndexOf("\\")));
while (folderList.size() > 0) {
(new File(folderList2.peek())).mkdirs(); // 如果文件夹不存在 则建立新文件夹
File folders = new File(folderList.peek());
String[] file = folders.list();
File temp = null;
try {
for (int i = 0; i < file.length; i++) {
if (folderList.peek().endsWith(File.separator)) {
temp = new File(folderList.peek() , file[i]);
} else {
temp = new File(folderList.peek() ,file[i]);
}
if (temp.isFile()) {
FileInputStream input = new FileInputStream(temp);
FileOutputStream output = new FileOutputStream(
folderList2.peek() + File.separator
+ (temp.getName()).toString());
byte[] b = new byte[10240];
while ((int len = input.read(b)) != -1)
output.write(b, 0, len);
output.flush();
output.close();
input.close();
if (!temp.delete())
//删除单个文件操作出错
}
else if (temp.isDirectory()) {// 如果是子文件夹
for (File f : temp.listFiles()) {
if (f.isDirectory()) {
folderList.add(f.getPath());
folderList2.add(folderList2.peek()
+ File.separator + f.getName());
}
else if (f.isFile()) {
FileInputStream input = new FileInputStream(f);
FileOutputStream output = new FileOutputStream(folderList2.peek()+File.separator+temp.getName()+File.separator+ f.getName());
byte[] b = new byte[10240];
while ((int len = input.read(b)) != -1)
output.write(b, 0, len);
output.flush();
output.close();
input.close();
if (!temp.delete())
//删除单个文件操作出错
}
}
}
}
} catch (IOException e) {
//复制整个文件夹内容操作出错
e.printStackTrace();
}
folderList.removeFirst();
folderList2.removeFirst();
}
File f = new File(%%1);
if (!f.delete()) {
for (File file : f.listFiles()) {
if (file.list().length == 0)
file.delete();
}
}
16.移动一个目录下所有的文件夹到另一个目录下
/*
import java.io.*;
import java.util.*;
*/
File movefolders=new File(%%1);
File[] movefoldersList=movefolders.listFiles();
for(int k=0;k<movefoldersList.length;k++){
if(movefoldersList[k].isDirectory()){
List<String>folderList=new ArrayList<String>();
folderList.add(movefoldersList[k].getPath());
List<String>folderList2=new ArrayList<String>();
folderList2.add(%%2+File.separator+movefoldersList[k].getName());
for(int j=0;j<folderList.size();j++){
(new File(folderList2.get(j))).mkdirs(); //如果文件夹不存在 则建立新文件夹
File folders=new File(folderList.get(j));
String[] file=folders.list();
File temp=null;
try {
for (int i = 0; i < file.length; i++) {
if(folderList.get(j).endsWith(File.separator))
temp=new File(folderList.get(j),file[i]);
else
temp=new File(folderList.get(j),file[i]);
FileInputStream input = new FileInputStream(temp);
if(temp.isFile()){
FileInputStream input = new FileInputStream(temp);
FileOutputStream output = new FileOutputStream(new File(folderList2.get(j),temp.getName().toString()));
byte[] b = new byte[10240];
while ( (int len = input.read(b)) != -1)
output.write(b, 0, len);
output.flush();
output.close();
input.close();
temp.delete();
}
else if(temp.isDirectory()){//如果是子文件夹
for (File f : temp.listFiles()) {
if (f.isDirectory()) {
folderList.add(f.getPath());
folderList2.add(folderList2.peek()
+ File.separator + f.getName());
}
else if (f.isFile()) {
FileInputStream input = new FileInputStream(f);
FileOutputStream output = new FileOutputStream(folderList2.peek()+File.separator+temp.getName()+File.separator+ f.getName());
byte[] b = new byte[10240];
while ((int len = input.read(b)) != -1)
output.write(b, 0, len);
output.flush();
output.close();
input.close();
if (!temp.delete())
//删除单个文件操作出错
}
}
}
}
catch (IOException e) {
//复制整个文件夹内容操作出错
e.printStackTrace();
}
}
movefoldersList[k].delete();
}
}
17.以一个文件夹的框架在另一个目录创建文件夹和空文件
/*
import java.io.*;
import java.util.*;
*/
boolean b=false;//不创建空文件
List<String>folderList=new ArrayList<String>();
folderList.add(%%1);
List<String>folderList2=new ArrayList<String>();
folderList2.add(%%2);
for(int j=0;j<folderList.size();j++){
(new File(folderList2.get(j))).mkdirs(); //如果文件夹不存在 则建立新文件夹
File folders=new File(folderList.get(j));
String[] file=folders.list();
File temp=null;
try {
for (int i = 0; i < file.length; i++) {
if(folderList.get(j).endsWith(File.separator))
temp=new File(folderList.get(j),file[i]);
else
temp=new File(folderList.get(j),file[i]);
if(temp.isFile() && b)
temp.createNewFile();
else if(temp.isDirectory()){//如果是子文件夹
folderList.add(folderList.get(j)+File.separator+file[i]);
folderList2.add(folderList2.get(j)+File.separator+file[i]);
}
}
}
catch (IOException e) {
//复制整个文件夹内容操作出错
e.printStackTrace();
}
}
18.复制文件
//import java.io.*;
File oldfile = new File(%%1);
try {
if (oldfile.exists()) { //文件存在时
FileInputStream inStream = new FileInputStream(oldfile); //读入原文件
FileOutputStream fs = new FileOutputStream(new File(%%2,oldfile.getName()));
byte[] buffer = new byte[10240];
int byteread;
while ( (byteread = inStream.read(buffer)) != -1)
fs.write(buffer, 0, byteread);
inStream.close();
}
}
catch (IOException e) {
//复制单个文件操作出错
e.printStackTrace();
}
19.复制一个目录下所有的文件到另一个目录
//import java.io.*;
File copyfiles=new File(%%1);
File targetfiles = new File(%%2);
if (!targetfiles.exists())
targetfiles.mkdirs();
File[] files=copyfiles.listFiles();
for(int i=0;i<files.length;i++){
if(files[i].isFile()){
try {
InputStream inStream = new FileInputStream(files[i]); //读入原文件
FileOutputStream fs = new FileOutputStream(new File(%%2,files[i].getName()));
byte[] buffer = new byte[10240];
int byteread;
while ( (byteread = inStream.read(buffer)) != -1)
fs.write(buffer, 0, byteread);
inStream.close();
} catch (IOException e) {
//复制单个文件操作出错
e.printStackTrace();
}
}
}
20.提取扩展名
String %%2=%%1.substring(%%1.lastIndexOf('.'));
21.提取文件名
String %%2=%%1.substring(%%1.lastIndexOf("\\")+1);
22.提取文件路径
String %%2=%%1.substring(0,%%1.lastIndexOf("\\"));
23.替换扩展名
//import java.io.*;
File replaceExt=new File(%%1);
replaceExt.renameTo(replaceExt.getName().split(".")[0]+"."+%%2);
24.追加路径
final String path=%%1.endsWith("\\")?%%1:%%1+"\\";
%%3=path+%%2;
25.移动文件
//import java.io.*;
File oldfile = new File(%%1);
try {
if (oldfile.exists()) { //文件存在时
InputStream inStream = new FileInputStream(oldfile); //读入原文件
FileOutputStream fs = new FileOutputStream(new File(%%2,oldfile.getName()));
byte[] buffer = new byte[10240];
int byteread;
while ( (byteread = inStream.read(buffer)) != -1)
fs.write(buffer, 0, byteread);
inStream.close();
oldfile.delete();
}
}
catch (IOException e) {
//复制单个文件操作出错
e.printStackTrace();
}
26.移动一个目录下所有文件到另一个目录
//import java.io.*;
File movefile=new File(%%1);
File[] movefiles=movefile.listFiles();
for(int i=0;i<movefiles.length;i++){
if(movefiles[i].isFile()){
File oldfile = new File(movefiles[i]);
try {
if (oldfile.exists()) { //文件存在时
InputStream inStream = new FileInputStream(oldfile); //读入原文件
FileOutputStream fs = new FileOutputStream(new File(%%2,oldfile.getName()));
byte[] buffer = new byte[10240];
int byteread;
while ( (byteread = inStream.read(buffer)) != -1)
fs.write(buffer, 0, byteread);
inStream.close();
oldfile.delete();
}
}
catch (IOException e) {
//复制单个文件操作出错
e.printStackTrace();
}
}
}
27.指定目录下搜索文件
//import java.io.*;
private static final String filter=%%1; //"*.*"
private static void doSearch(String path){
File file = new File(path);
if(file.exists()) {
if(file.isDirectory()) {
File[] fileArray = file.listFiles();
for(File f:fileArray) {
if(f.isDirectory()) {
doSearch(f.getPath());
} else {
if(f.getName().indexOf(filter) >= 0) {
//f.getPath()
}
}
//f.getPath()
}
//"The numbers of files had been found:" + countFiles
} else {
//"Couldn't open the path!"
}
} else {
System.err.println("目录不存在");
}
}
doSearch(%%1);
28.打开对话框
/*
import java.io.*;
import javax.swing.*;
*/
JFileChooser Jfc = new JFileChooser(); //建立选择档案对话方块盒 Jfc
Jfc.showDialog(null, %%1);
if (Jfc.getSelectedFile() != null) {
File %%2 = Jfc.getSelectedFile();
}
29.文件分割
//import java.io.*;
try {
File f=new File(%%1);
FileInputStream fileInputStream = new FileInputStream(f);
byte[] buffer = new byte[fileInputStream.available()];
FileInputStream.read(buffer);
fileInputStream.close();
String strFileName = f.getName();
FileOutputStream fileOutputStream = new FileOutputStream(new File(%%2+"\\"+ strFileName + "1"));
fileOutputStream.write(buffer,0,buffer.length/2);
fileOutputStream.close();
fileOutputStream = new FileOutputStream(new File(%%2+"\\"+ strFileName + "2"));
fileOutputStream.write(buffer, buffer.length/2, buffer.length-buffer.length/2);
fileOutputStream.close();
} catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
}
catch(IOException e){
e.printStackTrace();
}
30.文件合并
//import java.io.*;
String strFileName = %%1.substring(%%1.LastIndexOf("\\") + 1);
try {
FileInputStream fileInputStream1 = new FileInputStream(new File(%%2 + strFileName + "1"));
FileInputStream fileInputStream2 = new FileInputStream(new File(%%2 + strFileName + "2"));
byte[] buffer = new byte[fileInputStream1.available()+fileInputStream2.available()];
FileInputStream.read(buffer, 0, fileInputStream1.available());
FileInputStream2.read(buffer, fileInputStream1.available(), fileInputStream2.available());
fileInputStream.close();
fileInputStream2.close();
FileOutputStream fileOutputStream = new FileOutputStream(new File(%%2+"\\"+ strFileName));
fileOutputStream.write(buffer,0,buffer.length);
fileOutputStream.close();
}
catch(IOException e){
e.printStackTrace();
}
31.文件简单加密
/*
import java.io.*;
import javax.swing.*;
private static final String CharSet = "0123456789ABCDEF";
*/
JFileChooser jfc = new JFileChooser();
JFileChooser jfc2 = new JFileChooser();
jfc.showDialog(null, "请选择要加密编码的文件");
jfc2.showDialog(null, "请选择要输出的文件名");
if (jfc.getSelectedFile() != null && jfc2.getSelectedFile() != null) {
File oldfile = jfc.getSelectedFile();
FileInputStream inStream = null;
FileWriter fw = null;
try {
if (oldfile.exists()) {
inStream = new FileInputStream(oldfile);
fw = new FileWriter(jfc2.getSelectedFile());
byte[] sRead = new byte[10240];
int byteread;
while ((byteread = inStream.read(sRead)) != -1) {
StringBuilder smi = new StringBuilder(byteread * 2);
int ka = 3, kb = 5, kc = 2, kd = 7, js = 0;
if (byteread % 2 != 0)
js = 1;
for (int i = 0; i < byteread - 1; i += 2) {
char c1 = (char) sRead[i];
char c2 = (char) sRead[i + 1];
int tmp = ka * c1 + kc * c2;
while (tmp < 0)
tmp += 1024;
byte s1 = (byte) (tmp % 1024);
int js1 = (int) s1 >> 4 & 0xf;
smi.append(CharSet.substring(js1, js1 + 1));
int ks1 = s1 & 0xf;
smi.append(CharSet.substring(ks1, ks1 + 1));
tmp = kb * c1 + kd * c2;
while (tmp < 0)
tmp += 1024;
byte s2 = (byte) (tmp % 1024);
int js2 = (int) s2 >> 4 & 0xf;
smi.append(CharSet.substring(js2, js2 + 1));
int ks2 = s2 & 0xf;
smi.append(CharSet.substring(ks2, ks2 + 1));
}
if (js == 1) {
byte s3 = (byte) ((sRead[byteread - 1] - 4) % 1024);
int js3 = (int) s3 >> 4 & 0xf;
smi.append(CharSet.substring(js3, js3 + 1));
int ks3 = (int) s3 & 0xf;
smi.append(CharSet.substring(ks3, ks3 + 1));
}
fw.write(smi.toString());
}
fw.flush();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fw.close();
inStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
32.文件简单解密
/*
import java.io.*;
import javax.swing.*;
private static final String CharSet = "0123456789ABCDEF";
*/
private static int niyuan(int m, int n) {
int a, b, c, d, t, yu = 0, shang, mod;
a = m;
b = n;
mod = a;
c = 0;
d = 1;
while (b < 0)
b += a;
if (a % b == 0 || b % 2 == 0)
return 0;
while (b != 1) {
t = a % b;
shang = a / b;
a = b;
b = t;
yu = c - shang * d;
c = d;
d = yu;
}
if (yu < 0)
yu += mod;
return yu;
}
JFileChooser jfc = new JFileChooser();
JFileChooser jfc2 = new JFileChooser();
jfc.showDialog(null, "请选择要解码解密的文件");
jfc2.showDialog(null, "请选择要输出的文件名");
if (jfc.getSelectedFile() != null && jfc2.getSelectedFile() != null) {
FileOutputStream fw = null;
try {
FileInputStream fis = new FileInputStream(jfc.getSelectedFile());
fw = new FileOutputStream(jfc2
.getSelectedFile());
byte[] buffer = new byte[20480];
int ka = 3, kb = 5, kc = 2, kd = 7, js = 0, tmp;
int aany, ddny;
int r00 = ka * kc * kd;
int r01 = -ka * kb * kc;
int r10 = -kb * kc * kc;
int r11 = ka * kb * kc;
int x00 = ka * ka * kc * kd - ka * kb * kc * kc;
int x11 = ka * kb * kc * kd - kb * kb * kc * kc;
while (x00 % 2 == 0) {
x00 /= 2;
r00 /= 2;
r01 /= 2;
}
while (x11 % 2 == 0) {
x11 /= 2;
r10 /= 2;
r11 /= 2;
}
aany = x00;
ddny = x11;
if (niyuan(1024, aany) != 0 && niyuan(1024, ddny) != 0) {
int kn00 = r00 * niyuan(1024, x00);
int kn01 = r01 * niyuan(1024, x00);
int kn10 = r10 * niyuan(1024, x11);
int kn11 = r11 * niyuan(1024, x11);
ka = kn00;
kb = kn01;
kc = kn10;
kd = kn11;
} else {
JOptionPane.showMessageDialog(null, "无逆矩阵!");
System.exit(0);
}
while (ka < 0)
ka += 1024;
while (kb < 0)
kb += 1024;
while (kc < 0)
kc += 1024;
while (kd < 0)
kd += 1024;
ka %= 1024;
kb %= 1024;
kc %= 1024;
kd %= 1024;
try {
int byteread;
while ((byteread = fis.read(buffer)) != -1) {
int nLen = byteread / 2;
byte[] sming = new byte[nLen];
String chs=new String(buffer,"US-ASCII");
for (int i = 0; i < nLen; i++) {
byte bTmp;
if (byteread < 2)
bTmp = -1;
bTmp = (byte) (CharSet.indexOf(chs.substring(i * 2,i * 2+1)) * 16 + CharSet
.indexOf(chs.substring(i * 2 + 1,i * 2 + 2)));
sming[i] = bTmp;
}
if (nLen % 2 != 0)
js = 1;
for (int i = 0; i < nLen - 1; i += 2) {
char c1 = (char) sming[i];
char c2 = (char) sming[i + 1];
tmp = ka * c1 + kc * c2;
while (tmp < 0)
tmp += 1024;
char s1 = (char) (tmp % 1024);
fw.write(s1);
tmp = kb * c1 + kd * c2;
while (tmp < 0)
tmp += 1024;
char s2 = (char) (tmp % 1024);
fw.write(s2);
}
if (js == 1) {
char c3 = (char) ((sming[nLen - 1] - 4) % 1024);
fw.write(c3);
}
}
fw.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fis.close();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
33.读取ini文件属性
/*
import java.io.*;
import java.util.*;
import java.util.regex.*;
private static HashMap configMap=null;
private static FileReader fileReader = null;
*/
private static boolean readIni() {
if (configMap == null) {
configMap = new HashMap<String, ArrayList>();
String strLine = null;
String currentNode = null;
String previousNode = null;
ArrayList<Properties> vec = new ArrayList<Properties>();
int row = 0;
BufferedReader bufferedReader = new BufferedReader(fileReader);
try {
while ((strLine = bufferedReader.readLine()) != null) {
String oneLine = strLine.trim();
if (oneLine.length() >= 1) {
Pattern p = Pattern.compile("\\[\\s*.*\\s*\\]");
int nodelen = oneLine.split("[;]").length;
String[] strArray1 = new String[4];
if (nodelen == 1) {
oneLine = oneLine.split("[;]")[0].trim();
} else if (nodelen == 2) {
strArray1[3] = oneLine.split("[;]")[1].trim();
oneLine = oneLine.split("[;]")[0].trim();
}
Matcher m = p.matcher(oneLine);
if (m.matches()) {
strArray1[0] = "@Node";
strArray1[1] = oneLine;
strArray1[2] = "";
} else {
int keylen = oneLine.split("=").length;
if (keylen == 1) {
strArray1[0] = "@Key";
strArray1[1] = oneLine.split("=")[0];
strArray1[2] = "";
} else if (keylen == 2) {
strArray1[0] = "@Key";
strArray1[1] = oneLine.split("=")[0];
strArray1[2] = oneLine.split("=")[1];
} else {
strArray1[0] = "@ElementError";
strArray1[1] = "";
strArray1[2] = "";
strArray1[3] = "";
}
}
if (strArray1[0].equals("@Node")) {
previousNode = currentNode;
currentNode = strArray1[1];
if (row > 0) {
configMap.put(previousNode, (ArrayList)vec.clone());
vec.clear();
row = 0;
}
} else if (strArray1[0].equals("@Key") && row == 0) {
Properties ht = new Properties();
ht.setProperty(strArray1[1], strArray1[2]);
vec.add(ht);
row++;
} else if (strArray1[0].equals("@Key") && row > 0) {
Properties ht2 = new Properties();
ht2.put(strArray1[1], strArray1[2]);
vec.add(ht2);
row++;
}
}
}
configMap.put(currentNode, (ArrayList)vec.clone());
} catch (FileNotFoundException e) {
configMap = null;
e.printStackTrace();
return false;
} catch (IOException e) {
configMap = null;
e.printStackTrace();
return false;
}
}
return true;
}
try {
fileReader = new FileReader(%%1); //"Setup.ini"
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
if (readIni()) {
ArrayList<Properties> li = null;
li = (ArrayList<Properties>) configMap.get(%%2); //"[DataSource]"
for (Properties pro : li) {
if(pro.containsKey(%%3))
%%4=pro.getProperty(%%3);
}
}
try {
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
34.合并一个目录下所有的文件
//import java.io.*;
File combinefiles=new File(%%1);
File[] files=combinefiles.listFiles();
FileOutputStream fs;
try {
fs=new FileOutputStream(new File(%%2));
}
catch(IOException e){
e.printStackTrace();
}
for(int i=0;i<files.length;i++){
if(files[i].isFile()){
try {
FileInputStream inStream=new FileInputStream(files[i]);
byte[] buffer = new byte[10240];
int byteread;
while((byteread=inStream.read(buffer))!=-1)
fs.write(buffer,0,byteread);
inStream.close();
}
catch(Exception e){
//复制文件出错
e.printStackTrace();
}
}
}
try {
fs.close();
}
catch(IOException e){
e.printStackTrace();
}
35.写入ini文件属性
/*
import java.io.*;
import java.util.*;
import java.util.regex.*;
private static HashMap configMap=null;
*/
if (readIni()) {
ArrayList<Properties> li = null;
try {
FileWriter fw = new FileWriter(%%1);
li = (ArrayList<Properties>) configMap.get(%%2); //"[DataSource]"
fw.write("%%2\r\n");
for (Properties pro : li) {
if (pro.containsKey(%%3)) //"ip"
fw.write("%%3=" + %%6 + "\r\n");
}
fw.flush();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
36.获得当前路径
String %%1=getClass().getResource("/").getPath();
//String %%1=System.getProperty("user.dir");
37.读取XML数据库
/*
import java.io.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
private static Document document;
private static Element node;
*/
File xml_file = new File(%%1);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder = factory.newDocumentBuilder();
document = builder.parse(xml_file);
} catch (Exception e) {
e.printStackTrace();
}
String subNodeTag = %%2;
Element rootNode = document.getDocumentElement();
//%%2="Product" //%%4="id" //%%6="port"
//%%3="Name" //%%5="001"
NodeList nlist = rootNode.getElementsByTagName(subNodeTag);
int len = nlist.getLength();
for (int i = 0; i < len; i++) {
node = nlist.item(i);
String getNodeAttrValue = null;
NamedNodeMap attrList = node.getAttributes();
for (int j = 0; j < attrList.getLength(); j++) {
if (attrList.item(j).getNodeName().equals(%%4)) {
getNodeAttrValue = attrList.item(j).getNodeValue();
break;
}
}
if (getNodeAttrValue.equals(%%5)) {
nlist = node.getChildNodes();
String %%9=((Element) node).getElementsByTagName(%%3).item(0)
.getFirstChild().getNodeValue();
break;
}
}
38.写入XML数据库
/*
import java.io.*;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
private Document document;
private Element node;
*/
File xml_file = new File(%%1);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder builder = factory.newDocumentBuilder();
document = builder.parse(xml_file);
} catch (Exception e) {
e.printStackTrace();
}
String subNodeTag = %%2;
Element rootNode = document.getDocumentElement();
// %%2="Product" //%%4="pid" //%%6="author"
// %%3="Name" //%%5="price"
NodeList nlist = rootNode.getElementsByTagName(subNodeTag);
String ss = null;
int len = nlist.getLength();
for (int i = 0; i < len; i++) {
node = (Element) nlist.item(i);
//node.setAttribute(%%4, "0"+String.valueOf(i)); //ID格式化
String getNodeAttrValue = null;
NamedNodeMap attrList = node.getAttributes();
for (int j = 0; j < attrList.getLength(); j++) {
if (attrList.item(j).getNodeName().equals(%%4)) {
getNodeAttrValue = attrList.item(j).getNodeValue();
break;
}
}
if (getNodeAttrValue.equals("001")) {
nlist = node.getChildNodes();
ss = ((Element) node).getElementsByTagName(%%3).item(0)
.getFirstChild().getNodeValue();
ss = ((Element) node).getElementsByTagName(%%6).item(0)
.getFirstChild().getNodeValue();
ss = ((Element) node).getElementsByTagName(%%5).item(0)
.getFirstChild().getNodeValue();
((Element) node).getElementsByTagName(%%3).item(0)
.getFirstChild().setTextContent(%%7);
((Element) node).getElementsByTagName(%%6).item(0)
.getFirstChild().setTextContent(%%8);
((Element) node).getElementsByTagName(%%5).item(0)
.getFirstChild().setTextContent(%%9);
break;
}
}
if (ss == null) {
node = document.createElement(%%2);
node.setAttribute(%%4, String.valueOf(nlist.getLength() + 1));
node.appendChild(document.createTextNode("\n"));
Element server = document.createElement(%%3);
server.appendChild(document.createTextNode(%%7));
node.appendChild(server);
Element ipNode = document.createElement(%%6);
ipNode.appendChild(document.createTextNode(%%8));
node.appendChild(ipNode);
node.appendChild(document.createTextNode("\n"));
Element port = document.createElement(%%5);
port.appendChild(document.createTextNode(%%9));
node.appendChild(port);
node.appendChild(document.createTextNode("\n"));
rootNode.appendChild(node);
}
TransformerFactory tFactory = TransformerFactory.newInstance();
Transformer transformer = null;
try {
transformer = tFactory.newTransformer();
DOMSource source = new DOMSource(document);
StreamResult result = new StreamResult(xml_file);
transformer.transform(source, result);
} catch (IOException e) {
e.printStackTrace();
}
39.ZIP压缩文件
/*
import java.io.*;
import java.util.zip.*;
*/
//创建文件输入流对象
FileInputStream fis=new FileInputStream(%%1);
//创建文件输出流对象
FileOutputStream fos=new FileOutputStream(%%2);
//创建ZIP数据输出流对象
ZipOutputStream zipOut=new ZipOutputStream(fos);
//创建指向压缩原始文件的入口
ZipEntry entry=new ZipEntry(args[0]);
try {
zipOut.putNextEntry(entry);
//向压缩文件中输出数据
int nNumber;
byte[] buffer=new byte[1024];
while((nNumber=fis.read(buffer))!=-1)
zipOut.write(buffer,0,nNumber);
//关闭创建的流对象
zipOut.close();
fos.close();
fis.close();
}
catch(IOException e)
{
e.printStackTrace();
}
40.ZIP解压缩
/*
import java.io.*;
import java.util.zip.*;
*/
//创建文件输入流对象实例
FileInputStream fis=new FileInputStream(%%1);
//创建ZIP压缩格式输入流对象实例
ZipInputStream zipin=new ZipInputStream(fis);
//创建文件输出流对象实例
FileOutputStream fos=new FileOutputStream(%%2);
//获取Entry对象实例
ZipEntry entry=zipin.getNextEntry();
byte[] buffer=new byte[1024];
int nNumber;
try{
while((nNumber=zipin.read(buffer,0,buffer.length))!=-1)
fos.write(buffer,0,nNumber);
//关闭文件流对象
zipin.close();
fos.close();
fis.close();
}
catch(IOException e) {
e.printStackTrace();
}
41.获得应用程序完整路径
String %%1=System.getProperty("user.dir");
42.递归删除目录中的文件
/*
import java.io.*;
import java.util.*;
*/
ArrayList<String> folderList = new ArrayList<String>();
folderList.add(%%1);
for (int j = 0; j < folderList.size(); j++) {
File file = new File(folderList.get(j));
File[] files = file.listFiles();
ArrayList<File> fileList = new ArrayList<File>();
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
folderList.add(files[i].getPath());
} else {
fileList.add(files[i]);
}
}
for (File f : fileList) {
f.delete();
}
}
43.ZIP压缩文件夹
/*
import java.io.*;
import java.util.*;
import java.util.zip.*;
*/
public static String zipFileProcess(ArrayList outputZipFileNameList, String outputZipNameAndPath) {
ArrayList fileNames = new ArrayList();
ArrayList files = new ArrayList();
FileOutputStream fileOut = null;
ZipOutputStream outputStream = null;
FileInputStream fileIn = null;
StringBuffer sb = new StringBuffer(outputZipNameAndPath);
// FileInputStream fileIn =null;
try {
if (outputZipNameAndPath.indexOf(".zip") != -1) {
outputZipNameAndPath = outputZipNameAndPath;
} else {
sb.append(".zip");
outputZipNameAndPath = sb.toString();
}
fileOut = new FileOutputStream(outputZipNameAndPath);
outputStream = new ZipOutputStream(fileOut);
int outputZipFileNameListSize = 0;
if (outputZipFileNameList != null) {
outputZipFileNameListSize = outputZipFileNameList.size();
}
for (int i = 0; i < outputZipFileNameListSize; i++) {
File rootFile = new File(outputZipFileNameList.get(i).toString());
listFile(rootFile, fileNames, files, "");
}
for (int loop = 0; loop < files.size(); loop++) {
fileIn = new FileInputStream((File) files.get(loop));
outputStream.putNextEntry(new ZipEntry((String) fileNames.get(loop)));
byte[] buffer = new byte[1024];
while (fileIn.read(buffer) != -1) {
outputStream.write(buffer);
}
outputStream.closeEntry();
fileIn.close();
}
return outputZipNameAndPath;
} catch (IOException ioe) {
return null;
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
}
}
if (fileIn != null) {
try {
fileIn.close();
} catch (IOException e) {
}
}
}
}
private static void listFile(File parentFile, List nameList, List fileList, String directoryName) {
if (parentFile.isDirectory()) {
File[] files = parentFile.listFiles();
for (int loop = 0; loop < files.length; loop++) {
listFile(files[loop], nameList, fileList, directoryName + parentFile.getName() + "/");
}
} else {
fileList.add(parentFile);
nameList.add(directoryName + parentFile.getName());
}
}
String savePath=%%1;
ArrayList<String> outputZipFileName=new ArrayList<String>();
outputZipFileName.add(%%2);
zipFileProcess(outputZipFileName,savePath);
44.IDEA加密算法
private byte[] bytekey;
public byte[] getKey(String key){
int len1 =key.length();
if (len1>=16) {
key=key.substring(0, 16);
} else {
for (int i=0;i<16-len1;i++){
key=key.concat("0");
}
}
bytekey=key.getBytes();
return bytekey;
}
/**
* 加密String明文输入,String密文输出
* @param strMing
* @return
*/
public String getEncString(String strMing) {
byte[] byteMi = null;
byte[] byteMing = null;
String strMi = "";
try {
return byte2hex(IdeaEncrypt(bytekey,strMing.getBytes(),true) );
}
catch(Exception e){
e.printStackTrace();
}
finally {
byteMing = null;
byteMi = null;
}
return strMi;
}
/**
* 解密 以String密文输入,String明文输出
* @param strMi
* @return
*/
public String getDesString(String strMi) {
byte[] byteMing = null;
byte[] byteMi = null;
String strMing = "";
try {
String tmp= new String(IdeaEncrypt(bytekey,hex2byte(strMi.getBytes()),false ));
int len1=tmp.length();
return tmp.substring(0, len1-6);
}
catch(Exception e) {
e.printStackTrace();
}
finally {
byteMing = null;
byteMi = null;
}
return strMing;
}
private byte[] Encrypt(byte[] bytekey, byte[] inputBytes, boolean flag) {
byte[] encryptCode = new byte[8];
// 分解子密钥
int[] key = get_subkey(flag, bytekey);
// 进行加密操作
encrypt(key, inputBytes, encryptCode);
// 返回加密数据
return encryptCode;
}
private int bytesToInt(byte[] inBytes, int startPos) {
return ((inBytes[startPos] << & 0xff00) +
(inBytes[startPos + 1] & 0xff);
}
private void intToBytes(int inputInt, byte[] outBytes, int startPos) {
outBytes[startPos] = (byte) (inputInt >>>;
outBytes[startPos + 1] = (byte) inputInt;
}
private int x_multiply_y(int x, int y) {
if (x == 0) {
x = 0x10001 - y;
} else if (y == 0) {
x = 0x10001 - x;
} else {
int tmp = x * y;
y = tmp & 0xffff;
x = tmp >>> 16;
x = (y - x) + ((y < x) ? 1 : 0);
}
return x & 0xffff;
}
private void encrypt(int[] key, byte[] inbytes, byte[] outbytes) {
int k = 0;
int a = bytesToInt(inbytes, 0);
int b = bytesToInt(inbytes, 2);
int c = bytesToInt(inbytes, 4);
int d = bytesToInt(inbytes, 6);
for (int i = 0; i < 8; i++) {
a = x_multiply_y(a, key[k++]);
b += key[k++];
b &= 0xffff;
c += key[k++];
c &= 0xffff;
d = x_multiply_y(d, key[k++]);
int tmp1 = b;
int tmp2 = c;
c ^= a;
b ^= d;
c = x_multiply_y(c, key[k++]);
b += c;
b &= 0xffff;
b = x_multiply_y(b, key[k++]);
c += b;
c &= 0xffff;
a ^= b;
d ^= c;
b ^= tmp2;
c ^= tmp1;
}
intToBytes(x_multiply_y(a, key[k++]), outbytes, 0);
intToBytes(c + key[k++], outbytes, 2);
intToBytes(b + key[k++], outbytes, 4);
intToBytes(x_multiply_y(d, key[k]), outbytes, 6);
}
private int[] encrypt_subkey(byte[] byteKey) {
int[] key = new int[52];
if (byteKey.length < 16) {
byte[] tmpkey = new byte[16];
System.arraycopy(byteKey, 0, tmpkey,
tmpkey.length - byteKey.length, byteKey.length);
byteKey = tmpkey;
}
for (int i = 0; i < 8; i++) {
key[i] = bytesToInt(byteKey, i * 2);
}
for (int j = 8; j < 52; j++) {
if ((j & 0x7) < 6) {
key[j] = (((key[j - 7] & 0x7f) << 9) | (key[j - 6] >> 7)) &
0xffff;
} else if ((j & 0x7) == 6) {
key[j] = (((key[j - 7] & 0x7f) << 9) | (key[j - 14] >> 7)) &
0xffff;
} else {
key[j] = (((key[j - 15] & 0x7f) << 9) | (key[j - 14] >> 7)) &
0xffff;
}
}
return key;
}
private int fun_a(int a) {
if (a < 2) {
return a;
}
int b = 1;
int c = 0x10001 / a;
for (int i = 0x10001 % a; i != 1;) {
int d = a / i;
a %= i;
b = (b + (c * d)) & 0xffff;
if (a == 1) {
return b;
}
d = i / a;
i %= a;
c = (c + (b * d)) & 0xffff;
}
return (1 - c) & 0xffff;
}
private int fun_b(int b) {
return (0 - b) & 0xffff;
}
private int[] uncrypt_subkey(int[] key) {
int dec = 52;
int asc = 0;
int[] unkey = new int[52];
int aa = fun_a(key[asc++]);
int bb = fun_b(key[asc++]);
int cc = fun_b(key[asc++]);
int dd = fun_a(key[asc++]);
unkey[--dec] = dd;
unkey[--dec] = cc;
unkey[--dec] = bb;
unkey[--dec] = aa;
for (int k1 = 1; k1 < 8; k1++) {
aa = key[asc++];
bb = key[asc++];
unkey[--dec] = bb;
unkey[--dec] = aa;
aa = fun_a(key[asc++]);
bb = fun_b(key[asc++]);
cc = fun_b(key[asc++]);
dd = fun_a(key[asc++]);
unkey[--dec] = dd;
unkey[--dec] = bb;
unkey[--dec] = cc;
unkey[--dec] = aa;
}
aa = key[asc++];
bb = key[asc++];
unkey[--dec] = bb;
unkey[--dec] = aa;
aa = fun_a(key[asc++]);
bb = fun_b(key[asc++]);
cc = fun_b(key[asc++]);
dd = fun_a(key[asc]);
unkey[--dec] = dd;
unkey[--dec] = cc;
unkey[--dec] = bb;
unkey[--dec] = aa;
return unkey;
}
private int[] get_subkey(boolean flag, byte[] bytekey) {
if (flag) {
return encrypt_subkey(bytekey);
} else {
return uncrypt_subkey(encrypt_subkey(bytekey));
}
}
private byte[] ByteDataFormat(byte[] data, int unit) {
int len = data.length;
int padlen = unit - (len % unit);
int newlen = len + padlen;
byte[] newdata = new byte[newlen];
System.arraycopy(data, 0, newdata, 0, len);
for (int i = len; i < newlen; i++)
newdata[i] = (byte) padlen;
return newdata;
}
public byte[] IdeaEncrypt(byte[] idea_key, byte[] idea_data, boolean flag) {
byte[] format_key = ByteDataFormat(idea_key, 16);
byte[] format_data = ByteDataFormat(idea_data,;
int datalen = format_data.length;
int unitcount = datalen / 8;
byte[] result_data = new byte[datalen];
for (int i = 0; i < unitcount; i++) {
byte[] tmpkey = new byte[16];
byte[] tmpdata = new byte[8];
System.arraycopy(format_key, 0, tmpkey, 0, 16);
System.arraycopy(format_data, i * 8, tmpdata, 0,;
byte[] tmpresult = Encrypt(tmpkey, tmpdata, flag);
System.arraycopy(tmpresult, 0, result_data, i * 8,;
}
return result_data;
}
/**
* 二行制转字符串
* @param b
* @return
*/
public static String byte2hex(byte[] b) { //一个字节的数,
// 转成16进制字符串
String hs = "";
String stmp = "";
for (int n = 0; n < b.length; n++) {
//整数转成十六进制表示
stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
if (stmp.length() == 1)
hs = hs + "0" + stmp;
else
hs = hs + stmp;
}
return hs.toUpperCase(); //转成大写
}
public static byte[] hex2byte(byte[] b) {
if((b.length%2)!=0)
throw new IllegalArgumentException("长度不是偶数");
byte[] b2 = new byte[b.length/2];
for (int n = 0; n < b.length; n+=2) {
String item = new String(b,n,2);
// 两位一组,表示一个字节,把这样表示的16进制字符串,还原成一个进制字节
b2[n/2] = (byte)Integer.parseInt(item,16);
}
return b2;
}
public static void main(String[] args) {
IDEA idea = new IDEA();
idea.getKey("aadd");//生成密匙
String strEnc = idea.getEncString("1234567890");//加密字符串,返回String的密文
System.out.println(strEnc);
String strDes = idea.getDesString(strEnc);//把String 类型的密文解密
System.out.println(strDes);
// String key = "0000000000000000";
// String data = "11111111冯";
// byte[] bytekey = key.getBytes();
// byte[] bytedata = data.getBytes();
//
// IDEA idea = new IDEA();
// byte[] encryptdata = idea.IdeaEncrypt(bytekey, bytedata, true);
// byte[] decryptdata = idea.IdeaEncrypt(bytekey, encryptdata, false);
//
// System.out.println("--------------------------------");
//
// for (int i = 0; i < bytedata.length; i++) {
// System.out.print(" " + bytedata[i] + " ");
// }
//
// System.out.println("");
//
// for (int i = 0; i < encryptdata.length; i++) {
// System.out.print(" " + encryptdata[i] + " ");
// }
//
// System.out.println("");
//
// for (int i = 0; i < decryptdata.length; i++) {
// System.out.print(" " + decryptdata[i] + " ");
// }
}
45.验证Schema
/*
import javax.xml.*;
import javax.xml.transform.stream.*;
import javax.xml.validation.*;
import org.xml.sax.*;
*/
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
StreamSource ss = new StreamSource(%%1); //"mySchema.xsd"
try {
Schema schema = factory.newSchema(ss);
} catch (SAXException e) {
e.printStackTrace();
}
46.Grep
/*
import java.util.regex.*;
import java.io.*;
*/
throws Exception
Pattern pattern = Pattern.compile(%%1); // 第一个参数为需要匹配的字符串
Matcher matcher = pattern.matcher("");
String file = %%2;
BufferedReader br = null;
String line;
try {
br = new BufferedReader (new FileReader (file)); // 打开文件
} catch (IOException e) {
// 没有打开文件,则产生异常
System.err.println ("Cannot read '" + file
+ "': " + e.getMessage());
}
while ((line = br.readLine()) != null) { // 读入一行,直到文件结束
matcher.reset (line); // 匹配字符串
if (matcher.find()) { // 如果有匹配的字符串,则输出
//line
}
}
br.close(); // 关闭文件
47.直接创建多级目录
//import java.io.*;
File f=new File(%%1);
f.mkdirs();
48.批量重命名
//import java.io.*;
File target = new File("%%1");
String[] files = target.list();
File f = null;
String filename = null;
for (String file : files) {
f = new File(target, file);
filename = f.getName();
if (filename.substring(filename.lastIndexOf('.')).equalsIgnoreCase(
"%%2")) {
f.renameTo(new File(target.getAbsolutePath(), filename.replace(
"%%2", "%%3")));
// 这里可以反复使用replace替换,当然也可以使用正则表达式来替换了 ".txt" ".bat"
}
}
49.文本查找替换
//import java.nio.*;
String s1=%%1;
String s2=%%2;
String s3=%%3;
int pos=%%4;
/*变量i和j分别表示主串和模式串中当前字符串的位置,k表示匹配次数*/
int i,j,k=0;
i = pos;
j = 0;
//将s1转化成StringBuffer型进行操作
repStr = new StringBuffer(s1);
while(i<repStr.length()&&j<s2.length())
{
if(repStr.charAt(i) == s2.charAt(j))
{
++i; ++j;
if(j==s2.length())
{
/*j=s2.length()表示字符串匹配成功,匹配次数加1,此外对主串进行字符串替换*/
k = k+1;
repStr.replace(i-j,i,s3);
//将j进行重新赋值开始新的比较
j = 0;
}
}
else {i = i-j+1; j = 0;}
}
return k;
50.文件关联
//import java.io.*;
try {
Runtime.getRuntime().exec(%%1); //"assoc .txt =mynote" "assoc [.ext[=[filetype]]]"
} catch (IOException e) {
e.printStackTrace();
}
51.批量转换编码从GB2312到Unicode
52.设置JDK环境变量
@echo off
IF EXIST %1\bin\java.exe (
rem 如输入正确的 Java2SDK 安装目录,开始设置环境变量
@setx JAVA_HOME %1
@setx path %path%;%JAVA_HOME%\bin
@setx classpath %classpath%;.
@setx classpath %classpath%;%JAVA_HOME%\lib\tools.jar
@setx classpath %classpath%;%JAVA_HOME%\lib\dt.jar
@setx classpath %classpath%;%JAVA_HOME%\jre\lib\rt.jar
@echo on
@echo Java 2 SDK 环境参数设置完毕,正常退出。
) ELSE (
IF "%1"=="" (
rem 如没有提供安装目录,提示之后退出
@echo on
@echo 没有提供 Java2SDK 的安装目录,不做任何设置,现在退出环境变量设置。
) ELSE (
rem 如果提供非空的安装目录但没有bin\java.exe,则指定的目录为错误的目录
@echo on
@echo 非法的 Java2SDK 的安装目录,不做任何设置,现在退出环境变量设置。
)
)
//http://sourceforge.net/projects/jregistrykey/
//import ca.beq.util.win32.registry.*;
//import java.util.*;
1.打开键
RegistryKey r = new RegistryKey(RootKey.HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders");
2.添加键
RegistryKey r = new RegistryKey(RootKey.HKEY_CURRENT_USER, "Software\\BEQ Technologies");
r.create();
9.写入字符串值
RegistryKey r = new RegistryKey(RootKey.HKEY_CURRENT_USER, "Software\\BEQ Technologies");
RegistryValue v = new RegistryValue("myVal", ValueType.REG_SZ, "data");
r.setValue(v);
6.获取DWORD值
RegistryKey r = new RegistryKey(RootKey.HKEY_CURRENT_USER, "Software\\BEQ Technologies");
if(r.hasValue("myValue")) {
RegistryValue v = r.getValue("myValue");
v.setType(ValueType.REG_DWORD);
} // if
53.批量转换编码从Unicode到GB2312
54.删除空文件夹
//import java.io.*;
File f=new File(%%1);
if (isFolerNull(f)) {
for (File file :f.listFiles()) {
if (file.list().length == 0)
file.delete();
}
}
55.GB2312文件转UTF-8格式
//import java.io.*;
public class CharsetConvertor {
public static void main(String[] args) {
String str = "This is a test for *中网!@#$。,?";
try {
File f = new File("D:/test.txt");
FileOutputStream fio = new FileOutputStream(f);
String s = gbToUtf8(str);
fio.write(s.getBytes("UTF-8"));
fio.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
public static String gbToUtf8(String str) throws UnsupportedEncodingException {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < str.length(); i++) {
String s = str.substring(i, i + 1);
if (s.charAt(0) > 0x80) {
byte[] bytes = s.getBytes("Unicode");
String binaryStr = "";
for (int j = 2; j < bytes.length; j += 2) {
// the first byte
String hexStr = getHexString(bytes[j + 1]);
String binStr = getBinaryString(Integer.valueOf(hexStr, 16));
binaryStr += binStr;
// the second byte
hexStr = getHexString(bytes[j]);
binStr = getBinaryString(Integer.valueOf(hexStr, 16));
binaryStr += binStr;
}
// convert unicode to utf-8
String s1 = "1110" + binaryStr.substring(0, 4);
String s2 = "10" + binaryStr.substring(4, 10);
String s3 = "10" + binaryStr.substring(10, 16);
byte[] bs = new byte[3];
bs[0] = Integer.valueOf(s1, 2).byteValue();
bs[1] = Integer.valueOf(s2, 2).byteValue();
bs[2] = Integer.valueOf(s3, 2).byteValue();
String ss = new String(bs, "UTF-8");
sb.append(ss);
} else {
sb.append(s);
}
}
return sb.toString();
}
private static String getHexString(byte b) {
String hexStr = Integer.toHexString(b);
int m = hexStr.length();
if (m < 2) {
hexStr = "0" + hexStr;
} else {
hexStr = hexStr.substring(m - 2);
}
return hexStr;
}
private static String getBinaryString(int i) {
String binaryStr = Integer.toBinaryString(i);
int length = binaryStr.length();
for (int l = 0; l < 8 - length; l++) {
binaryStr = "0" + binaryStr;
}
return binaryStr;
}
}
56.UTF-8文件转GB2312格式
private String utf8Togb2312(String str){
StringBuffer sb = new StringBuffer();
for(int i=0; i<str.length(); i++) {
char c = str.charAt(i);
switch (c) {
case '+':
sb.append(' ');
break;
case '%':
try {
sb.append((char)Integer.parseInt(
str.substring(i+1,i+3),16));
}
catch (NumberFormatException e) {
throw new IllegalArgumentException();
}
i += 2;
break;
default:
sb.append(c);
break;
}
}
// Undo conversion to external encoding
String result = sb.toString();
String res=null;
try{
byte[] inputBytes = result.getBytes("8859_1");
res= new String(inputBytes,"UTF-8");
}
catch(Exception e){}
return res;
}
57.获取文件路径的父路径
String %%2=%%1.substring(0,%%1.lastIndexOf("\\"));
58.Unicode文件转UTF-8格式
try {
// Convert from Unicode to UTF-8
String string = "abc\u5639\u563b";
byte[] utf8 = string.getBytes("UTF-8");
// Convert from UTF-8 to Unicode
string = new String(utf8, "UTF-8");
} catch (UnsupportedEncodingException e) {
}
/**
* unicode 转换成 utf-8
* @author fanhui
* 2007-3-15
* @param theString
* @return
*/
public static String unicodeToUtf8(String theString) {
char aChar;
int len = theString.length();
StringBuffer outBuffer = new StringBuffer(len);
for (int x = 0; x < len;) {
aChar = theString.charAt(x++);
if (aChar == '\\') {
aChar = theString.charAt(x++);
if (aChar == 'u') {
// Read the xxxx
int value = 0;
for (int i = 0; i < 4; i++) {
aChar = theString.charAt(x++);
switch (aChar) {
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
value = (value << 4) + aChar - '0';
break;
case 'a':
case 'b':
case 'c':
case 'd':
case 'e':
case 'f':
value = (value << 4) + 10 + aChar - 'a';
break;
case 'A':
case 'B':
case 'C':
case 'D':
case 'E':
case 'F':
value = (value << 4) + 10 + aChar - 'A';
break;
default:
throw new IllegalArgumentException(
"Malformed \\uxxxx encoding.");
}
}
outBuffer.append((char) value);
} else {
if (aChar == 't')
aChar = '\t';
else if (aChar == 'r')
aChar = '\r';
else if (aChar == 'n')
aChar = '\n';
else if (aChar == 'f')
aChar = '\f';
outBuffer.append(aChar);
}
} else
outBuffer.append(aChar);
}
return outBuffer.toString();
}
59.CRC循环冗余校验
/*
import java.nio.*;
import java.util.zip.*;
*/
try {
FileInputStream in = new FileInputStream(%%1);
FileChannel channel = in.getChannel();
CRC32 crc = new CRC32();
int length = (int)channel.size();
MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, length);
for(int i = 0;i<length;i++)
{
int c = buffer.get(i);
crc.update(c);
}
System.out.println("crc校验和:"+(Long.toHexString(crc.getValue())).toUpperCase());
} catch (Exception e) {
e.printStackTrace();
}
60.判断是否为空文件
//import java.io.*;
FileReader fr=new FileReader(%%1);
if(fr.read()==1)
//空白文件
61.终止程序
Runtime.exec("taskkill /F /IM %%1.exe");
62.定时关机
import java.awt.*;
import java.awt.event.*;
import java.awt.geom.*;
import java.util.*;
import javax.swing.*;
public class ClockFrame extends JFrame {
private JComboBox hourBox, minuteBox, secondBox;
private int hour, minute, second, totalSeconds, currentSeconds;
private long argue;
private GregorianCalendar calendar;
private boolean change = true;
private static final int WIDTH = 200;
private static final int HEIGHT = 150;
public ClockFrame() {
setTitle("关机定时");
setSize(200, 150);
Container contentPanel = getContentPane();
JPanel timePanel = new JPanel();
timePanel.setLayout(new GridLayout(4, 2));
JLabel minuteLable = new JLabel("设置分钟");
timePanel.add(minuteLable);
minuteBox = new JComboBox();
timePanel.add(minuteBox);
for (int i = 0; i < 60; i++) {
minuteBox.addItem(i);
}
minuteBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
minute = ((Integer) minuteBox.getSelectedItem()).intValue();
}
});
JLabel secondLable = new JLabel("设置秒钟");
timePanel.add(secondLable);
secondBox = new JComboBox();
timePanel.add(secondBox);
for (int i = 0; i < 60; i++) {
secondBox.addItem(i);
}
secondBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
second = ((Integer) secondBox.getSelectedItem()).intValue();
}
});
contentPanel.add(timePanel, BorderLayout.CENTER);
JButton check = new JButton("确定");
contentPanel.add(check, BorderLayout.SOUTH);
check.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
JButton check=(JButton) evt.getSource();
if (check.getText().equals("确定")) {
calendar = new GregorianCalendar();
int currentSeconds = calendar.get(Calendar.HOUR_OF_DAY)
* 3600 + calendar.get(Calendar.MINUTE) * 60
+ calendar.get(Calendar.SECOND);
totalSeconds = hour * 3600 + minute * 60 + second;
if (totalSeconds - currentSeconds >= 0) {
argue = (totalSeconds - currentSeconds) * 1000;
JOptionPane.showMessageDialog(ClockFrame.this,
"您设置的时间为 " + hour + ":" + minute + ":" + second
+ "\n程序将在后台运行,并在此时自动关闭计算机!", "设置成功",
JOptionPane.INFORMATION_MESSAGE);
hideFrame();
}
try {
// Thread.sleep(argue);//这句没用
Runtime.getRuntime().exec(
"shutdown.exe -s -c \"我要关机了噢!不好意思!\" -t "
+ totalSeconds);
check.setText("取消");
} catch (Exception e) {
e.printStackTrace();
}
}else{
try {
Runtime.getRuntime().exec("shutdown.exe -a");
check.setText("确定");
} catch (Exception e) {
e.printStackTrace();
}
}
}
});
}
private void hideFrame() {
this.setVisible(false);
}
public static void main(String[] args) {
JFrame frame = new ClockFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationByPlatform(true);
frame.show();
}
}
63.显示进程列表
//import java.io.*;
BufferedReader br=null;
try {
Process proc=Runtime.getRuntime().exec("tasklist");
br=new BufferedReader(new InputStreamReader(proc.getInputStream()));
@SuppressWarnings("unused")
String line=null;
while((line=br.readLine())!=null){
//br.readLine()
}
} catch (IOException e) {
e.printStackTrace();
}finally{
if(br!=null){
try {
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
64.遍历文件夹列出文件大小
65.目录下所有文件移动到整合操作
/*
import java.io.*;
import java.util.*;
import javax.swing.*;
*/
JFileChooser Jfc = new JFileChooser("请选择源路径"); // 建立选择档案对话方块盒 Jfc
Jfc.showDialog(null, %%1);
if (!Jfc.getSelectedFile() != null) {
return;
}
String %%1 = Jfc.getSelectedFile().getParent();
Jfc = new JFileChooser("请选择目标路径"); // 建立选择档案对话方块盒 Jfc
Jfc.showDialog(null, %%1);
if (!Jfc.getSelectedFile() != null) {
return;
}
String %%2 = Jfc.getSelectedFile().getParent();
66.对目标压缩文件解压缩到指定文件夹
/*
import java.io.*;
import java.util.zip.*;
*/
String zipFileName=%%1;
String extPlace=%%2;
File myFolderPath = new File(extPlace);
try {
if (!myFolderPath.exists()) {
myFolderPath.mkdir();
}
} catch (Exception e) {
//新建目录操作出错
e.printStackTrace();
return;
}
try {
ZipInputStream in = new ZipInputStream(new FileInputStream(
zipFileName));
ZipEntry entry = null;
while ((entry = in.getNextEntry()) != null) {
String entryName = entry.getName();
File file = new File(extPlace , entryName);
if (entry.isDirectory()) {
file.mkdirs();
} else {
FileOutputStream os = new FileOutputStream(file);
// Transfer bytes from the ZIP file to the output
// file
byte[] buf = new byte[10240];
int len;
while ((len = in.read(buf)) > 0) {
os.write(buf, 0, len);
}
os.close();
in.closeEntry();
}
}
} catch (IOException e) {
e.printStackTrace();
}
67.创建目录副本整合操作
/*
import java.io.*;
import java.util.*;
import javax.swing.*;
*/
JFileChooser Jfc = new JFileChooser("请选择源路径"); // 建立选择档案对话方块盒 Jfc
Jfc.showDialog(null, %%1);
if (!Jfc.getSelectedFile() != null) {
return;
}
String %%1 = Jfc.getSelectedFile().getParent();
Jfc = new JFileChooser("请选择目标路径"); // 建立选择档案对话方块盒 Jfc
Jfc.showDialog(null, %%1);
if (!Jfc.getSelectedFile() != null) {
return;
}
String %%2 = Jfc.getSelectedFile().getParent();
68.打开网页
//import java.io.*;
try{
String command = "C:\\Program Files\\Internet Explorer\\Iexplore.exe "+%%1;
Runtime.getRuntime().exec(command);
} catch (IOException ex) {
ex.printStackTrace();
}
69.删除空文件夹整合操作
/*
import java.io.*;
import java.util.*;
import javax.swing.*;
*/
70.获取磁盘所有分区,把结果放在数组drives中
String root; //root代表盘符路径
for(i=0;i<20;i++) //0-20代表最大的盘符数
{
root.Format("%c:\\",allfenqu[i]);
if(GetDriveType(root)==5)
allfenqu[i]='\0';
}
但我用这样的代码时结果却无法去掉光驱盘符,allfenqu[]中还是会包含光驱盘符:
String root;
for(i=0;i<20;i++)
{
root=allfenqu[i]+":\\";
if(GetDriveType(root)==5)
allfenqu[i]='\0';
}
71.激活一个程序或程序关联的文件
//import java.io.*;
try {
Runtime.getRuntime().exec(%%1);
} catch (IOException e) {
e.printStackTrace();
}
72.MP3播放
//必须下载 jmf包
//import javax.media.bean.playerbean.MediaPlayer; //必须下载 jmf 媒体播放包
MediaPlayer player;
player = new MediaPlayer();
setLayout(new FlowLayout());
try{
player.setMediaLocation("file:/F:\\音乐\\mp3\\黑白配.mp3");// <<file:/>>不能删除 音频文件路径
} catch (Exception e) {
System.err.println("文件不存在");
}
player.start();
player.stop();
73.WAV播放
/*
import javax.sound.sampled.*;
import java.io.*;
*/
private AudioFormat format;
private byte[] samples;
private String filename;
try {
// open the audio input stream
AudioInputStream stream =AudioSystem.getAudioInputStream(new File(filename));
format = stream.getFormat();
// get the audio samples
samples = getSamples(stream);
}
catch (UnsupportedAudioFileException ex) {
ex.printStackTrace();
}
catch (IOException ex) {
ex.printStackTrace();
}
private byte[] getSamples(AudioInputStream audioStream) {
// get the number of bytes to read
int length = (int)(audioStream.getFrameLength() * format.getFrameSize());
// read the entire stream
byte[] samples = new byte[length];
DataInputStream is = new DataInputStream(audioStream);
try {
is.readFully(samples);
}
catch (IOException ex) {
ex.printStackTrace();
}
// return the samples
return samples;
}
public void play(InputStream source) {
// use a short, 100ms (1/10th sec) buffer for real-time
// change to the sound stream
int bufferSize = format.getFrameSize() *
Math.round(format.getSampleRate() / 10);
byte[] buffer = new byte[bufferSize];
// create a line to play to
SourceDataLine line;
try {
DataLine.Info info =
new DataLine.Info(SourceDataLine.class, format);
line = (SourceDataLine)AudioSystem.getLine(info);
line.open(format, bufferSize);
}
catch (LineUnavailableException ex) {
ex.printStackTrace();
return;
}
// start the line
line.start();
// copy data to the line
try {
int numBytesRead = 0;
while (numBytesRead != -1) {
numBytesRead =
source.read(buffer, 0, buffer.length);
if (numBytesRead != -1) {
line.write(buffer, 0, numBytesRead);
}
}
}
catch (IOException ex) {
ex.printStackTrace();
}
// wait until all data is played, then close the line
line.drain();
line.close();
}
throws Exception
String filename=%%1;
InputStream stream =new ByteArrayInputStream(sound.getSamples());
// play the sound
sound.play(stream);
74.写图像到剪切板
/*
import java.awt.*;
import java.awt.datatransfer.*;
import java.io.*;
private final Image image;
*/
Transferable trans = new Transferable() {
public DataFlavor[] getTransferDataFlavors() {
return new DataFlavor[] { DataFlavor.imageFlavor };
}
public boolean isDataFlavorSupported(DataFlavor flavor) {
return DataFlavor.imageFlavor.equals(flavor);
}
public Object getTransferData(DataFlavor flavor)
throws UnsupportedFlavorException, IOException {
if (isDataFlavorSupported(flavor))
return image;
throw new UnsupportedFlavorException(flavor);
}
};
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(trans,
null);
75.从剪贴板复制图像到窗体
76.删除文件夹下的所有文件且不删除文件夹下的文件夹
/*
import java.io.*;
import java.util.*;
*/
LinkedList<String> folderList = new LinkedList<String>();
folderList.add(%%1);
while (folderList.size() > 0) {
File file = new File((String)folderList.poll());
File[] files = file.listFiles();
ArrayList<File> fileList = new ArrayList<File>();
for (int i = 0; i < files.length; i++) {
if (file
相关推荐
在使用"bin文件转txt文件工具"时,用户可以加载bin文件到软件界面,然后执行转换操作。由于该工具支持任意大小的文件,这意味着无论bin文件有多大,只要内存和硬盘空间允许,都能进行转换。这对于处理大型数据集或者...
这样的批处理文件简化了操作,使得用户无需手动输入命令就能完成转换。 在实际应用中,这个工具可能适用于以下场景: 1. **固件更新**:当固件以BIN格式提供,但编程器或烧录器需要S19格式时,此工具可以方便地...
它提供了丰富的命令行工具,用于执行各种LAS文件的操作和格式转换,如点云过滤、分类、裁剪、合并、统计分析等。`Lastool` 的强大之处在于其灵活性和高效性,使得用户能够在命令行环境中快速处理大规模的激光雷达...
转换过程通常需要借助专门的转换工具,如压缩包中的"A文件转Excel.exe"。这个程序可能是设计用来解析A文件格式,并将其数据导出到Excel工作簿中。使用这类工具时,用户需要按照软件的指引,选择要转换的A文件,然后...
【标题】:NC文件转TXT详解 在处理气象、海洋、气候等科学数据时,我们经常遇到NC(NetCDF)文件格式。这种文件格式是一种自我描述的、机器无关的、可扩展的数据存储格式,用于存储多维数组。然而,有时我们需要将...
本篇文章将深入探讨如何使用C#操作LibreOffice组件来实现文件格式之间的转换,包括Word、HTML、Excel、PDF以及图像等。 LibreOffice是一款开源的办公套件,它提供了API接口,允许开发者通过编程方式与LibreOffice...
在Windows上,还有许多图形界面工具可以进行此操作,比如Hex Editors(十六进制编辑器),如HxD,它可以读取和编辑二进制文件,同时也能导出为其他格式,包括BIN。 在进行转换时,需要注意以下几点: 1. 数据的含义...
DBC文件是一种数据库通讯格式,主要用于存储汽车ECU(电子控制单元)中的数据,例如汽车的传感器数据、控制信号等。这种文件格式在汽车行业非常常见,主要用于调试和数据分析。转换DBC文件到Excel文件是为了让非专业...
实现PDF文件和图片的互相转化 可实现功能: 1.PDF转换成图片: 将PDF文件按页转换成.Png图片格式,转换结束会有提示 (转换过的文件将自动移动到对应的文件夹,防止多次转换) 2.图片转换成PDF: 可以将单张照片(....
本话题主要涉及"adf文件转TIFF文件",这是一种将特定的数据格式转换为广泛使用的图像格式的过程。下面我们将深入探讨ADF(Arc/Info Binary Grid)文件和TIFF(Tagged Image File Format)文件,以及如何进行这种转换...
这种类型文件可以提供关于如何运行和操作“dxf2xyz.exe”这个转换程序的信息,包括可能的选项、参数设置和常见问题解答。用户应先查阅这个帮助文件以了解转换过程。 "adinit26.dat"可能是一个AutoCAD相关的初始化...
《文件目录结构转文本网页:技术解析与应用》 在现代数字生活中,管理和呈现大量文件目录结构变得日益重要。为了方便浏览和分享这些信息,将文件目录结构转化为文本网页,尤其是HTML格式,成为了一种高效的方式。...
在实际项目中,文件转Base64操作通常用于上传文件至服务器,存储在数据库中,或者在网络中以文本形式传输。了解并熟练掌握这一技巧对于C#开发者来说是非常重要的。在标签中提到的"C#文件转base64 文件转换"是一个...
1. 打开.dat文件:使用适当的文件I/O操作读取文件内容。 2. 解析二进制数据:根据文件的结构解析数字,这可能需要理解文件的字节顺序(如大端或小端)和数据类型(如整数、浮点数)。 3. 转换数字:将二进制表示的...
在实际操作中,确保你正确指定了文件路径和名称,避免出现找不到文件的错误。同时,转换过程中需要注意数据的完整性,确保转换前后文件的内容没有丢失或被篡改。在某些情况下,可能还需要关注文件的字节顺序,尤其是...
至于压缩包子文件的文件名称列表,"grb文件转换为nc文件"可能包含了转换过程的脚本或说明,而"nc文件裁剪"可能包含裁剪操作的代码示例或指南。如果你需要更深入地了解这些操作,你可以打开这些文件查看具体的代码...
在IT领域,转换文件格式是常见的操作之一,例如将TXT文本转换为BIN文件。TXT文件是一种常见的纯文本格式,用于存储人类可读的数据,而BIN文件通常代表二进制文件,可能包含计算机程序、数据或其他特定格式的信息。...
压缩包子文件的文件名称“HEXתBIN.exe”暗示这可能是一个Windows操作系统下的可执行文件,它的功能就是执行HEX到二进制的转换操作。用户只需运行这个程序,并提供输入的HEX文件路径和输出的二进制文件路径,就可以...
在IT领域,文件格式转换是常见的操作之一,特别是在软件开发、数据存储和传输过程中。"TXT转换BIN文件"的主题涉及到两个基本的文件类型:纯文本文件(TXT)和二进制文件(BIN)。理解这两者的差异和转换过程是至关...