`
蛋呢823
  • 浏览: 72075 次
  • 性别: Icon_minigender_1
  • 来自: 长沙
社区版块
存档分类
最新评论
收藏列表
标题 标签 来源
用文本 做数据持久化 Java 小例子:数据持久化(保存数据到文件)
import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
 
/**
 * 持久化示例。如何将内存中的数据保存起来,并没有一定的格式,任何人
 * 都可以根据自己的喜好来制定。持久化需要文件操作,所以请务必先弄懂
 * 如何读写文件。
 */
public class Persistant {
 
    // 文件名可随意指定,你可以用文本编辑器打开这个文件(注意,记事本无法处理换行)
    static String filename = "persons.data";
 
    public static void main(String[] args) throws Exception {
        // 将这个程序运行两遍。
        // 第一遍它会创建一些 Person 对象并保存到文件;
        // 第二遍它会从文件中读取对象数据并显示出来。
        if (!new File(filename).exists()) {
            createAndSave();
        } else {
            readAndShow();
        }
    }
 
    // 生成并保存 Person 对象
    private static void createAndSave() throws IOException {
        List<Person> persons = createPersons();
        savePersons(persons);
    }
 
    // 读取并显示 Person 对象
    private static void readAndShow() throws IOException {
        List<Person> persons = readPersons();
        showPersons(persons);
    }
 
    // 创建要保存的 Person 对象
    private static List<Person> createPersons() {
        List<Person> result = new ArrayList<Person>();
        result.add(new Person("张三", new Date(), true));
        result.add(new Person("李四", new Date(), false));
        result.add(new Person("王五", new Date(), true));
        return result;
    }
 
    // 保存 Person 对象到文件。保存格式为:
    // 1、每个 Person 一行
    // 2、每行依次存放 name、birthday、male 三个属性值,用 tab 隔开
    // 3、birthday 属性保存的是毫秒数,male 属性保存的是字符串
    private static void savePersons(List<Person> persons) throws IOException {
 
        // 生成文件内容
        String data = "";
        for (Person person : persons) {
            data += getPersonString(person) + "/n";
        }
 
        // 保存文件内容
        FileWriter writer = new FileWriter(filename);
        writer.write(data);
        writer.close();
        System.out.println("对象保存完毕。");
    }
 
    private static String getPersonString(Person person) {
        return person.getName() + "/t" + person.getBirthday().getTime() + "/t" + person.isMale();
    }
 
    // 从文件中读取 Person 对象
    private static List<Person> readPersons() throws IOException {
        List<Person> result = new ArrayList<Person>();
 
        BufferedReader reader = new BufferedReader(new FileReader(filename));
        String line;
        while ((line = reader.readLine()) != null) {
            result.add(getPersonFromString(line));
        }
 
        return result;
    }
 
    // 通过一行文件内容生成一个 Person 对象
    private static Person getPersonFromString(String line) {
        String[] parts = line.split("/t");  // 获取被分隔的三个部分
 
        return new Person(
                parts[0],                               // 姓名
                new Date(Long.parseLong(parts[1])),     // 出生日期
                Boolean.parseBoolean(parts[2])          // 是否为男性
        );
    }
 
    // 显示 Person 对象
    private static void showPersons(List<Person> persons) {
        for (Person person : persons) {
            System.out.println(person.getName() + ", " +
                    person.getBirthday() + ", " +
                    (person.isMale() ? "男" : "女"));
        }
    }
}
 
// 要持久化的类
class Person {
 
    private String name;        // 姓名
 
    private Date birthday;      // 生日
 
    private boolean male;       // true 表示男性,false 表示女性
 
    Person(String name, Date birthday, boolean male) {
        this.name = name;
        this.birthday = birthday;
        this.male = male;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public Date getBirthday() {
        return birthday;
    }
 
    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
 
    public boolean isMale() {
        return male;
    }
 
    public void setMale(boolean male) {
        this.male = male;
    }
}
读取XML文件,获取属性值 Find the value of a specific attribute in an XML file in java
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;

public class GetVersion {
    public static void main(String[] args) throws Exception {
        XPath xpath = XPathFactory.newInstance().newXPath();
        Document doc = DocumentBuilderFactory.newInstance()
            .newDocumentBuilder().parse("file:////tmp/whatever.xml");
        // xml like: <behavior name="Fred" version="2.0" ....>
        String version = xpath.evaluate("//behavior/@version", doc);
        System.out.println(version);
    }
}
二分查找- while方式 算法 一个经典的二分查找算法
1:     public static int binarySearch(int[] a, int key) {
2:         int low = 0;
3:         int high = a.length - 1;
4: 
5:         while (low <= high) {
6:             int mid = (low + high) / 2;
7:             int midVal = a[mid];
8:
9:             if (midVal < key)
10:                 low = mid + 1;
11:             else if (midVal > key)
12:                 high = mid - 1;
13:             else
14:                 return mid; // key found
15:         }
16:         return -(low + 1);  // key not found.
17:     }
JUnit4 参数化测试 junit JUnit4中参数化测试
package org.test;

import java.util.Arrays;
import java.util.Collection;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
/**
 * 参数化测试的类必须有Parameterized测试运行器修饰
 *
 */
@RunWith(Parameterized.class)
public class AddTest3 {

	private int input1;
	private int input2;
	private int expected;
	
	/**
	 * 准备数据。数据的准备需要在一个方法中进行,该方法需要满足一定的要求:

		 1)该方法必须由Parameters注解修饰
		 2)该方法必须为public static的
		 3)该方法必须返回Collection类型
		 4)该方法的名字不做要求
		 5)该方法没有参数
	 * @return
	 */
	@Parameters
	@SuppressWarnings("unchecked")
	public static Collection prepareData(){
		Object [][] object = {{-1,-2,-3},{0,2,2},{-1,1,0},{1,2,3}};
		return Arrays.asList(object);
	}
	
	public AddTest3(int input1,int input2,int expected){
		this.input1 = input1;
		this.input2 = input2;
		this.expected = expected;
	}
	@Test
	public void testAdd(){
		Add add = new Add();
		int result = add.add(input1, input2);
		Assert.assertEquals(expected,result);
	}
	
}

字符串格式化
String.format("Today, I saw %s and %s at %d o'clock", "Jim", "Kate", 2);
小数百分比格式化
public   static  String percent( double  p1,  double  p2)  {
	String str;
	double  p3  =  p1  /  p2;
	NumberFormat nf  =  NumberFormat.getPercentInstance();
	nf.setMinimumFractionDigits( 2 );
	str  =  nf.format(p3);
	return  str;
}
文件操作大全 io
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] << 8) & 0xff00) +
(inBytes[startPos + 1] & 0xff);
}

private void intToBytes(int inputInt, byte[] outBytes, int startPos) {
outBytes[startPos] = (byte) (inputInt >>> 8);
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, 8);

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, 8);

byte[] tmpresult = Encrypt(tmpkey, tmpdata, flag);
System.arraycopy(tmpresult, 0, result_data, i * 8, 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
三个线程按顺序打印ABC 多线程 做了论坛上迅雷笔试关于线程的题目,发现自己程序的问题,大家来讨论讨论
public class Seqwork  { 
	private boolean flag[] = new boolean[3] ;
	int maxruncount = 10 ;
	
	public static void main(String[] args) {
		Seqwork main = new Seqwork() ;
		main.work() ;
	}

	void work(){
		flag[0] = true ;
		new Thread(new WorkThread(0,"A")).start() ;
		new Thread(new WorkThread(1,"B")).start() ;
		new Thread(new WorkThread(2,"C")).start() ;
	}
	
	class WorkThread implements Runnable{
		String name ;
		int i ;
		int nextone ;
		boolean isendworker = false;
		public WorkThread(int i,String name){
			this.i = i ;
			this.name = name ;
			this.nextone = (i+1)%flag.length ;
			if (i==flag.length-1) {
				isendworker = true ;
			}
		}
		
		@Override
		public void run() {
			int count = 0;
			while (count < maxruncount) {
				synchronized (flag) {
					if (flag[i]) {
						System.out.print(this.name);
						count++;
						if (isendworker) {
							System.out.println("");
						}
						flag[i] = false;
						flag[nextone] = true;
						flag.notifyAll();
					} else {
						try {
							flag.wait();
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}
			}
		}
	} 
}
四舍五入 Java 保留2位小数

import java.math.BigDecimal;
import java.math.MathContext;
import java.math.RoundingMode;

public class BigDec {
	public static void main(String[] args){
		//		四舍五入方法
		MathContext v = new MathContext(5,RoundingMode.HALF_DOWN);
		BigDecimal a = new BigDecimal("0.87234643298346",v);
		System.out.println(a);

		
	}

}

Double 格式化 format JAVA DOUBLE 格式化
public class Demo {

	/**
	 * @param args
	 */
	public static void main( String[] args ) {

		double d = 3.262724538037E-4;
		DecimalFormat df = new DecimalFormat( "#.################" );
		System.out.println( df.format( d ) );
	}
}
HashMap putForNullKey hashmap HashMap put
/**
     * Offloaded version of put for null keys
     */
    private V putForNullKey(V value) {
        for (Entry<K,V> e = table[0]; e != null; e = e.next) {
            if (e.key == null) {
                V oldValue = e.value;
                e.value = value;
                e.recordAccess(this);
                return oldValue;
            }
        }
        modCount++;
        addEntry(0, null, value, 0);
        return null;
    }
失血模型 领域模型 总结一下最近关于domain object以及相关的讨论
public class ItemDaoHibernateImpl implements ItemDao extends HibernateDaoSupport {
    public Item getItemById(Long id) {
        return (Item) getHibernateTemplate().load(Item.class, id);
    }
    public Collection findAll() {
        return (List) getHibernateTemplate().find("from Item");
    }
    public void updateItem(Item item) {
        getHibernateTemplate().update(item);
    }
}
Global site tag (gtag.js) - Google Analytics