服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|JAVA教程|ASP教程|

服务器之家 - 编程语言 - JAVA教程 - Java最全文件操作实例汇总

Java最全文件操作实例汇总

2020-03-01 11:16wangtao041 JAVA教程

这篇文章主要介绍了Java最全文件操作,总结分析了大量实例,详细汇总了Java针对文件的各种常用操作,需要的朋友可以参考下

本文实例汇总了Java文件操作。分享给大家供大家参考,具体如下:

1.创建文件夹

?
1
2
3
4
5
6
7
8
9
10
11
//import java.io.*;
File myFolderPath = new File(%%1);
try {
if (!myFolderPath.exists()) {
myFolderPath.mkdir();
}
}
catch (Exception e) {
System.out.println("新建目录操作出错");
e.printStackTrace();
}

2.创建文件

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//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);
resultFile.close();
}
catch (Exception e) {
System.out.println("新建文件操作出错");
e.printStackTrace();
}

3.删除文件

?
1
2
3
4
5
6
7
8
9
//import java.io.*;
File myDelFile = new File(%%1);
try {
myDelFile.delete();
}
catch (Exception e) {
System.out.println("删除文件操作出错");
e.printStackTrace();
}

4.删除文件夹

?
1
2
3
4
5
6
7
8
9
//import java.io.*;
File delFolderPath = new File(%%1);
try {
delFolderPath.delete(); //删除空文件夹
}
catch (Exception e) {
System.out.println("删除文件夹操作出错");
e.printStackTrace();
}

5.删除一个文件下夹所有的文件夹

?
1
2
3
4
5
6
7
8
//import java.io.*;
File delfile=new File(%%1);
File[] files=delfile.listFiles();
for(int i=0;i<files.length;i++){
if(files[i].isDirectory()){
files[i].delete();
}
}

6.清空文件夹

?
1
2
3
4
5
6
7
8
9
10
11
12
//import java.io.*;
File delfilefolder=new File(%%1);
try {
if (!delfilefolder.exists()) {
delfilefolder.delete();
}
delfilefolder.mkdir();
}
catch (Exception e) {
System.out.println("清空目录操作出错");
e.printStackTrace();
}

7.读取文件

?
1
2
3
4
5
6
7
8
9
10
11
//import java.io.*;
// 逐行读取数据
FileReader fr = new FileReader(%%1);
BufferedReader br = new BufferedReader(fr);
String %%2 = br.readLine();
while (%%2 != null) {
%%3
%%2 = br.readLine();
}
br.close();
fr.close();

8.写入文件

?
1
2
3
4
5
6
7
8
9
10
//import java.io.*;
// 将数据写入文件
try {
FileWriter fw = new FileWriter(%%1);
fw.write(%%2);
fw.flush();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}

9.写入随机文件

?
1
2
3
4
5
6
7
8
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.读取文件属性

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//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.写入属性

?
1
2
3
4
5
6
7
8
//import java.io.*;
File filereadonly=new File(%%1);
try {
boolean b=filereadonly.setReadOnly();
}
catch (Exception e) {
System.out.println("拒绝写访问:"+e.printStackTrace());
}

12.枚举一个文件夹中的所有文件

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//import java.io.*;
//import java.util.*;
LinkedList<String> folderList = new LinkedList<String>();
folderList.add(%%1);
while (folderList.size() > 0) {
File file = new File(folderList.peek());
folderList.removeLast();
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) {
%%2=f.getAbsoluteFile();
%%3
}
}

13.复制文件夹

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
//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(
folderList2.peek() + File.separator
+ (temp.getName()).toString());
byte[] b = new byte[5120];
int len;
while ((len = input.read(b)) != -1) {
output.write(b, 0, len);
}
output.flush();
output.close();
input.close();
}
if (temp.isDirectory()) {// 如果是子文件夹
for (File f : temp.listFiles()) {
if (f.isDirectory()) {
folderList.add(f.getPath());
folderList2.add(folderList2.peek()
+ File.separator + f.getName());
}
}
}
}
} catch (Exception e) {
//System.out.println("复制整个文件夹内容操作出错");
e.printStackTrace();
}
folderList.removeFirst();
folderList2.removeFirst();
}

14.复制一个文件夹下所有的文件夹到另一个文件夹下

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
//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()){
ArrayList<String>folderList=new ArrayList<String>();
folderList.add(copyfoldersList[k].getPath());
ArrayList<String>folderList2=new ArrayList<String>();
folderList2.add(%%2+"/"+copyfoldersList[k].getName());
for(int j=0;j<folderList.length;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.separator+file[i]);
}
FileInputStream input = new FileInputStream(temp);
if(temp.isFile()){
FileInputStream input = new FileInputStream(temp);
FileOutputStream output = new FileOutputStream(folderList2.get(j) + "/" +
(temp.getName()).toString());
byte[] b = new byte[5120];
int len;
while ( (len = input.read(b)) != -1) {
output.write(b, 0, len);
}
output.flush();
output.close();
input.close();
}
if(temp.isDirectory()){//如果是子文件夹
folderList.add(folderList.get(j)+"/"+file[i]);
folderList2.add(folderList2.get(j)+"/"+file[i]);
}
}
}
catch (Exception e) {
System.out.println("复制整个文件夹内容操作出错");
e.printStackTrace();
}
}
}
}

15.移动文件夹

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
//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(
folderList2.peek() + File.separator
+ (temp.getName()).toString());
byte[] b = new byte[5120];
int len;
while ((len = input.read(b)) != -1) {
output.write(b, 0, len);
}
output.flush();
output.close();
input.close();
if (!temp.delete())
System.out.println("删除单个文件操作出错!");
}
if (temp.isDirectory()) {// 如果是子文件夹
for (File f : temp.listFiles()) {
if (f.isDirectory()) {
folderList.add(f.getPath());
folderList2.add(folderList2.peek()
+ File.separator + f.getName());
}
}
}
}
} catch (Exception e) {
// System.out.println("复制整个文件夹内容操作出错");
e.printStackTrace();
}
folderList.removeFirst();
folderList2.removeFirst();
}
File f = new File(%%1);
if (!f.delete()) {
for (File file : f.listFiles()) {
if (file.list().length == 0) {
System.out.println(file.getPath());
file.delete();
}
}
}

16.移动一个文件夹下所有的文件夹到另一个目录下

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
//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()){
ArrayList<String>folderList=new ArrayList<String>();
folderList.add(movefoldersList[k].getPath());
ArrayList<String>folderList2=new ArrayList<String>();
folderList2.add(%%2+"/"+movefoldersList[k].getName());
for(int j=0;j<folderList.length;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.separator+file[i]);
}
FileInputStream input = new FileInputStream(temp);
if(temp.isFile()){
FileInputStream input = new FileInputStream(temp);
FileOutputStream output = new FileOutputStream(folderList2.get(j) + "/" +
(temp.getName()).toString());
byte[] b = new byte[5120];
int len;
while ( (len = input.read(b)) != -1) {
output.write(b, 0, len);
}
output.flush();
output.close();
input.close();
temp.delete();
}
if(temp.isDirectory()){//如果是子文件夹
folderList.add(folderList.get(j)+"/"+file[i]);
folderList2.add(folderList2.get(j)+"/"+file[i]);
}
}
}
catch (Exception e) {
System.out.println("复制整个文件夹内容操作出错");
e.printStackTrace();
}
}
movefoldersList[k].delete();
}
}

17.以一个文件夹的框架在另一个目录创建文件夹和空文件

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
//import java.io.*;
//import java.util.*;
boolean b=false;//不创建空文件
ArrayList<String>folderList=new ArrayList<String>();
folderList.add(%%1);
ArrayList<String>folderList2=new ArrayList<String>();
folderList2.add(%%2);
for(int j=0;j<folderList.length;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.separator+file[i]);
}
FileInputStream input = new FileInputStream(temp);
if(temp.isFile()){
if (b) temp.createNewFile();
}
if(temp.isDirectory()){//如果是子文件夹
folderList.add(folderList.get(j)+"/"+file[i]);
folderList2.add(folderList2.get(j)+"/"+file[i]);
}
}
}
catch (Exception e) {
System.out.println("复制整个文件夹内容操作出错");
e.printStackTrace();
}
}

18.复制文件

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
//import java.io.*;
int bytesum = 0;
int byteread = 0;
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[5120];
int length;
while ( (byteread = inStream.read(buffer)) != -1) {
bytesum += byteread; //字节数 文件大小
System.out.println(bytesum);
fs.write(buffer, 0, byteread);
}
inStream.close();
}
}
catch (Exception e) {
System.out.println("复制单个文件操作出错");
e.printStackTrace();
}

19.复制一个文件夹下所有的文件到另一个目录

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//import java.io.*;
File copyfiles=new File(%%1);
File[] files=copyfiles.listFiles();
for(int i=0;i<files.length;i++){
if(!files[i].isDirectory()){
int bytesum = 0;
int byteread = 0;
try {
InputStream inStream = new FileInputStream(files[i]); //读入原文件
FileOutputStream fs = new FileOutputStream(new File(%%2,files[i].getName());
byte[] buffer = new byte[5120];
int length;
while ( (byteread = inStream.read(buffer)) != -1) {
bytesum += byteread; //字节数 文件大小
System.out.println(bytesum);
fs.write(buffer, 0, byteread);
}
inStream.close();
} catch (Exception e) {
System.out.println("复制单个文件操作出错");
e.printStackTrace();
}
}
}

20.提取扩展名

复制代码 代码如下:
String %%2=%%1.substring(%%1.lastIndexOf(".")+1);

21.提取文件名
复制代码 代码如下:
String %%2=%%1.substring(%%1.lastIndexOf("//")+1);

22.提取文件路径
复制代码 代码如下:
String %%2=%%1.substring(0,%%1.lastIndexOf("//"));

23.替换扩展名

 

?
1
2
3
//import java.io.*;
File replaceExt=new File(%%1);
replaceExt.renameTo(replaceExt.getName().split(".")[0]+"."+%%2);

24.追加路径

?
1
2
final String path=%%1.endsWith("//")?%%1:%%1+"//";
%%3=path+%%2;

25.移动文件

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//import java.io.*;
int bytesum = 0;
int byteread = 0;
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[5120];
int length;
while ( (byteread = inStream.read(buffer)) != -1) {
bytesum += byteread; //字节数 文件大小
//System.out.println(bytesum);
fs.write(buffer, 0, byteread);
}
inStream.close();
oldfile.delete();
}
}
catch (Exception e) {
System.out.println("复制单个文件操作出错");
e.printStackTrace();
}

26.移动一个文件夹下所有文件到另一个目录

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
//import java.io.*;
File movefile=new File(%%1);
File[] movefiles=movefile.listFiles();
for(int i=0;i<movefiles.length;i++){
if(movefiles[i].isFile()){
int bytesum = 0;
int byteread = 0;
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[5120];
int length;
while ( (byteread = inStream.read(buffer)) != -1) {
bytesum += byteread; //字节数 文件大小
//System.out.println(bytesum);
fs.write(buffer, 0, byteread);
}
inStream.close();
oldfile.delete();
}
}
catch (Exception e) {
System.out.println("复制单个文件操作出错");
e.printStackTrace();
}
}
}

27.指定目录下搜索文件

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
//import java.io.*;
String filter="*.*";
String path=%%1;
File file = new File(path);
if(file.exists()) {
if(file.isDirectory()) {
File[] fileArray = file.listFiles();
for(File f:fileArray) {
if(f.isDirectory()) {
doSearch(filter,f.getPath());
} else {
if(f.getName().indexOf(filter) >= 0) {
countFiles++;
result.append(f.getPath() + "/r/n");
}
}
statusShow1.setText(f.getPath());
}
statusShow2.setText("The numbers of files had been found:" + countFiles);
} else {
System.out.println("Couldn't open the path!");
}
} else {
System.out.println("The path had been apointed was not Exist!");
}

28.打开对话框

?
1
2
3
4
5
6
//import java.io.*;
//import javax.swing.*;
JFileChooser Jfc = new JFileChooser(); //建立选择档案对话方块盒 Jfc
if (Jfc.isFileSelectionEnabled()) {
File %%1 = Jfc.getSelectedFile();
}

29.文件分割

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//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) {
System.out.print("using FileStreamDemo src des");
e.printStackTrace();
}
catch(IOException e){
e.printStackTrace();
}

30.文件合并

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//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.文件简单加密

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
//import java.io.*
try {
File f=new File((new File(%%1)).getPath()+"//enc_"+(new File(%%1)).getName().split("//")[1]);
String strFileName = f.getName();
FileInputStream fileInputStream = new FileInputStream(%%2+"//"+strFilename);
byte[] buffer = new byte[fileInputStream.available()];
FileInputStream.read(buffer);
fileInputStream.close();
for(int i=0;i<buffer.length;i++)
{
int ibt=buffer[i];
ibt+=100;
ibt%=256;
buffer[i]=(byte)ibt;
}
FileOutputStream fileOutputStream = new FileOutputStream(f);
fileOutputStream.write(buffer,0,buffer.length);
fileOutputStream.close();
}
catch(ArrayIndexOutOfBoundException e){
e.printStackTrace();
}
catch(IOException e){
e.printStackTrace();
}

32.文件简单解密

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
//import java.io.*
try {
File f=new File(%%1);
String strFileName = f.getName();
FileInputStream fileInputStream = new FileInputStream(%%2+"//enc_"+strFilename);
byte[] buffer = new byte[fileInputStream.available()];
FileInputStream.read(buffer);
fileInputStream.close();
for(int i=0;i<buffer.length;i++)
{
int ibt=buffer[i];
ibt-=100;
ibt+=256;
ibt%=256;
buffer[i]=(byte)ibt;
}
FileOutputStream fileOutputStream = new FileOutputStream(f);
fileOutputStream.write(buffer,0,buffer.length);
fileOutputStream.close();
}
catch(ArrayIndexOutOfBoundException e){
e.printStackTrace();
}
catch(IOException e){
e.printStackTrace();
}

33.写入ini文件属性

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
//import java.io.*;
//import java.util.*;
//import java.util.regex.*;
if (configMap == null) {
String WriteBuffer = "";
configMap = new HashMap<String, Serializable>();
String strLine = null;
String currentNode = null;
String previousNode = null;
Vector<Properties> vec = new Vector<Properties>();
int row = 0;
FileReader fileReader = null;
try {
fileReader = new FileReader("Config.ini");
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
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, vec.elementAt(0));
vec.clear();
row = 0;
}
WriteBuffer += (oneLine + "/r/n");
} else if (strArray1[0].equals("@Key") && row == 0) {
Properties ht = new Properties();
ht.setProperty(strArray1[1], strArray1[2]);
if (strArray1[1].equals(%%1)) {
WriteBuffer += (%%1+"=" + %%2 + "/r/n");
} else
WriteBuffer += (oneLine + "/r/n");
vec.add(0, ht);
row++;
} else if (strArray1[0].equals("@Key") && row > 0) {
Properties ht2 = new Properties();
ht2.put(strArray1[1], strArray1[2]);
vec.clear();
vec.add(0, ht2);
WriteBuffer += (oneLine + "/r/n");
row++;
}
}
}
configMap.put(currentNode, vec.elementAt(0));
} catch (FileNotFoundException e) {
configMap = null;
e.printStackTrace();
} catch (IOException e) {
configMap = null;
e.printStackTrace();
} finally {
vec.clear();
try {
bufferedReader.close();
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileWriter fw = new FileWriter("Config.ini");
fw.write(WriteBuffer);
fw.flush();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

34.读取ini文件属性

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
//import java.io.*;
//import java.util.*;
//import java.util.regex.*;
//private HashMap configMap=null;
private Map<String, Serializable> configMap=null;
String %%2=null;
if (configMap == null) {
configMap = new HashMap<String, Serializable>();
String strLine = null;
String currentNode = null;
String previousNode = null;
Vector<Properties> vec = new Vector<Properties>();
int row = 0;
FileReader fileReader = null;
try {
fileReader = new FileReader("Config.ini");
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
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, vec.elementAt(0));
vec.clear();
row = 0;
}
} else if (strArray1[0].equals("@Key") && row == 0) {
Properties ht = new Properties();
ht.setProperty(strArray1[1], strArray1[2]);
if(strArray1[1].equals(%%1))
{
%%2=strArray1[2];
return;
}
vec.add(0, ht);
row++;
} else if (strArray1[0].equals("@Key") && row > 0) {
Properties ht2 = new Properties();
ht2.put(strArray1[1], strArray1[2]);
vec.clear();
vec.add(0, ht2);
row++;
}
}
}
configMap.put(currentNode, vec.elementAt(0));
} catch (FileNotFoundException e) {
configMap = null;
e.printStackTrace();
} catch (IOException e) {
configMap = null;
e.printStackTrace();
} finally {
vec.clear();
try {
bufferedReader.close();
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

35.合并一个文件下所有的文件

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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()){
int bytesum=0;
int byteread=0;
try {
FileInputStream inStream=new FileInputStream(files[i]);
byte[] buffer = new byte[5120];
int length;
while((byteread=inStream.read(buffer))!=-1){
bytesum+=byteread;
fs.write(buffer,0,byteread);
}
inStream.close();
}
catch(Exception e){
//复制文件出错
e.printStackTrace();
}
}
}
try {
fs.close();
}
catch(IOException e){
{
e.printStackTrace();
}

36.写入ini文件属性

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
//import java.io.*;
//import java.util.*;
//import java.util.regex.*;
//private HashMap configMap=null;
private Map<String, Serializable> configMap=null;
if(configMap==null) {
String strLine=null;
String currentNode=null;
String previousNode=null;
Vector<Properties> vec=new Vector<Properties>();
int row=0;
FileReader fileReader = null;
try {
fileReader = new FileReader(%%1);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
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,vec.elementAt(0));
//"size:"+configMap.size()
vec.clear();
row=0;
}
} else if(strArray1[0].equals("@Key") && row==0) {
Properties ht=new Properties();
ht.setProperty(strArray1[1],strArray1[2]);
vec.add(0,ht);
row++;
} else if(strArray1[0].equals("@Key") && row>0) {
Properties ht2=new Properties();
ht2.put(strArray1[1],strArray1[2]);
vec.clear();
vec.add(0,ht2);
row++;
}
}
}
configMap.put(currentNode,vec.elementAt(0));
} catch (FileNotFoundException e) {
configMap=null;
e.printStackTrace();
} catch (IOException e) {
configMap=null;
e.printStackTrace();
} finally {
vec.clear();
try {
bufferedReader.close();
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
String nodeKey="["+%%2+"]";
Properties ht=null;
if(configMap.containsKey(nodeKey)) {
ht=(Properties)configMap.get(nodeKey);
} else {
ht=(Properties)configMap.put(nodeKey,%%3);
}
try {
ht.setProperty(%%3,%%4);
} catch (NullPointException e) {
e.printStackTrace();
}
FileWriter fw= null;
BufferedWriter bw= null;
try {
fw = new FileWriter(%%1);
bw=new BufferedWriter(fw);
} catch (IOException e) {
e.printStackTrace();
}
Set keys=configMap.keySet();
Iterator ite=keys.iterator();
while(ite.hasNext()) {
String oneKey=(String)ite.next();
try {
bw.write(oneKey+"/n");
} catch (IOException e) {
e.printStackTrace();
}
ht=(Properties)configMap.get(oneKey);
ht.list(new PrintWriter(bw,true));
}

37.获得当前路径

复制代码 代码如下:
String %%1=this.getClass().getResource("/").getPath();

38.读取XML数据库

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
//import java.io.*;
//import javax.xml.parsers.*;
//import org.xml.sax.*;
//import org.w3c.dom.*;
private Document document;
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="serverList" //%%4="id" //%%6="port"
//%%3="server" //%%5="ipaddr"
NodeList nlist=rootNode.getElementsByTagName(subNodeTag);
int len=nlist.getLength();
Node x=null;
for(int i=0;i<len;i++) {
x=nlist.item(i);
String getNodeAttrValue=null;
NamedNodeMap attrList=node.getAttributes();
for(int j=0;j<attrList.getLength();j++) {
if(attrList.item(j).getNodeName().compareTo(%%7)==0) {
getNodeAttrValue=attrList.item(j).getNodeValue();
break;
}
}
if(getNodeAttrValue.compareTo(%%8)==0)
break;
}
String %%9=null;
if(x!=null) {
NodeList nlist=node.getChildNodes();
int len=nlist.getLength();
Node currentNode;
String nodeName;
for(int i=0;i<len;i++) {
currentNode=nlist.item(i);
nodeName=currentNode.getNodeName();
if(nodeName.equals(%%5)==0) {
%%9=document.getElementValue(currentNode);
break;
}
}
}

39.写入XML数据库

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
//import java.io.*;
//import javax.xml.parsers.*;
//import org.xml.sax.*;
//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="serverList" //%%4="id" //%%6="port"
//%%3="server" //%%5="ipaddr"
NodeList nlist=rootNode.getElementByTagName(subNodeTag);
node=document.createElement(%%3);
node.setAttribute(%%4,nlist.getLength()+1).toString());
node.appendChild(document.createTextNode("/n");
Element ipNode=document.createElement(%%5);
ipNode.appendChild(document.createTextNode(%%8));
node.appendChild(ipNode);
node.appendChild(document,createTextNode("/n");
Element port=document.createElement(%%6);
port.appendChild(document.createTextNode(%%9));
node.appendChild(port);
node.appendChild(document,createTextNode("/n");
nlist.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(Exception e) {
e.printStackTrace();
}

40.ZIP压缩文件

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
//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]);
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)
{
System.out.println(e);
}

41.获得应用程序完整路径

复制代码 代码如下:
String %%1=System.getProperty("user.dir");

42.ZIP解压缩

 

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//import java.io.*;
//import java.util.zip.*;
try{
//创建文件输入流对象实例
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;
while((nNumber=zipin.read(buffer,0,buffer.length))!=-1)
fos.write(buffer,0,nNumber);
//关闭文件流对象
zipin.close();
fos.close();
fis.close();
}
catch(IOException e) {
System.out.println(e);
}

43.递归删除目录中的文件

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//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压缩文件夹

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
//import java.io.*;
//import org.apache.tools.zip.ZipOutputStream;
//这个包在ant.jar里,要到官方网下载
//import java.util.zip.*;
try {
String zipFileName = %%2; //打包后文件名字
File f=new File(%%1);
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName));
String base= "";
if (f.isDirectory()) {
File[] fl = f.listFiles();
out.putNextEntry(new org.apache.tools.zip.ZipEntry(base + "/"));
base = base.length() == 0 ? "" : base + "/";
for (int i = 0; i < fl.length; i++) {
zip(out, fl[i], base + fl[i].getName());
}
}else {
out.putNextEntry(new org.apache.tools.zip.ZipEntry(base));
FileInputStream in = new FileInputStream(f);
int b;
while ( (b = in.read()) != -1) {
out.write(b);
}
in.close();
}
out.close();
}catch (Exception ex) {
ex.printStackTrace();
}

44.Java验证DTD

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
//import java.io.*;
//import javax.xml.parsers.*;
//import org.xml.sax.*;
//import org.w3c.dom.*;
try {
InputStream in=new FileInputStream(filePath);
SAXReader saxReader = new SAXReader();
this.document = saxReader.read(in);
DocumentBuilderFactory factory = null;
factory = DocumentBuilderFactory.newInstance();
//进行dtd检查
factory.setValidating(true);
} catch (Exception e) {
}

45.验证Schema

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
//import java.io.*;
//import javax.xml.parsers.*;
//import org.xml.sax.*;
//import org.w3c.dom.*;
String xsdFileName = /"Q:////_dev_stu////xsdtest////src////note.xsd/";
try {
//创建默认的XML错误处理器
XMLErrorHandler errorHandler = new XMLErrorHandler();
//获取基于 SAX 的解析器的实例
SAXParserFactory factory = SAXParserFactory.newInstance();
//解析器在解析时验证 XML 内容。
factory.setValidating(true);
//指定由此代码生成的解析器将提供对 XML 名称空间的支持。
factory.setNamespaceAware(true);
//使用当前配置的工厂参数创建 SAXParser 的一个新实例。
SAXParser parser = factory.newSAXParser();
//创建一个读取工具
SAXReader xmlReader = new SAXReader();
//获取要校验xml文档实例
Document xmlDocument = (Document) xmlReader.read(new File(xmlFileName));
//设置 XMLReader 的基础实现中的特定属性。核心功能和属性列表可以在 http://sax.sourceforge.net/?selected=get-set 中找到。
parser.setProperty(
/"http://java.sun.com/xml/jaxp/properties/schemaLanguage",
/"http://www.w3.org/2001/XMLSchema");
parser.setProperty(
/"http://java.sun.com/xml/jaxp/properties/schemaSource",
/"file:/" + xsdFileName);
//创建一个SAXValidator校验工具,并设置校验工具的属性
SAXValidator validator = new SAXValidator(parser.getXMLReader());
//设置校验工具的错误处理器,当发生错误时,可以从处理器对象中得到错误信息。
validator.setErrorHandler(errorHandler);
//校验
validator.validate(xmlDocument);
XMLWriter writer = new XMLWriter(OutputFormat.createPrettyPrint());
//如果错误信息不为空,说明校验失败,打印错误信息
if (errorHandler.getErrors().hasContent()) {
System.out.println(/"XML文件通过XSD文件校验失败!/");
writer.write(errorHandler.getErrors());
} else {
System.out.println(/"Good! XML文件通过XSD文件校验成功!/");
}
} catch (Exception ex) {
System.out.println(/"XML文件: /" + xmlFileName + /" 通过XSD文件:/" + xsdFileName + /"检验失败。/n原因: /" + ex.getMessage
());
ex.printStackTrace();
}
}

46.Grep

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
//import java.util.regex.*;
//import java.io.*;
/**
* Simple implementation of the ubiquitous grep command.
* First argument is the regular expression to search for (remember to
* quote and/or escape as appropriate). All following arguments are
* filenames to read and search for the regular expression.
*
* Created: April, 2002
* @author Ron Hitchens (ron@ronsoft.com)
* @version $Id: SimpleGrep.java,v 1.1 2002/05/07 02:21:08 ron Exp $
*/
public static void main (String [] argv)
throws Exception
{
if (argv.length < 2) { // 如果参数行没有输入参数,结束程序
System.out.println ("Usage: regex file [ ... ]");
return;
}
Pattern pattern = Pattern.compile (argv [0]); // 第一个参数为需要匹配的字符串
Matcher matcher = pattern.matcher ("");
// 一次读取各个文件
for (int i = 1; i < argv.length; i++) {
String file = argv [i]; // 第2个参数开始,均为文件名。
BufferedReader br = null;
String line;
try {
br = new BufferedReader (new FileReader (file)); // 打开文件
} catch (IOException e) {
// 没有打开文件,则产生异常
System.err.println ("Cannot read '" + file
+ "': " + e.getMessage());
continue;
}
while ((line = br.readLine()) != null) { // 读入一行,直到文件结束
matcher.reset (line); // 匹配字符串
if (matcher.find()) { // 如果有匹配的字符串,则输出
System.out.println (file + ": " + line);
}
}
br.close(); // 关闭文件
}
}

47.直接创建多级目录

?
1
2
3
//import java.io.*;
File f=new File(%%1);
f.mkdirs();

48.批量重命名

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//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(fl, 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.文本查找替换

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
//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.文件关联

?
1
2
3
4
5
6
//import java.io.*;
try {
Runtime.getRuntime().exec(%%1); //"assoc .txt =mynote" "assoc [.ext[=[filetype]]]"
} catch (IOException e) {
e.printStackTrace();
}

52.设置JDK环境变量

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
@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.打开键

?
1
2
RegistryKey r = new RegistryKey(RootKey.HKEY_LOCAL_MACHINE,
"SOFTWARE//Microsoft//Windows//CurrentVersion//Explorer//Shell Folders");

2.添加键

?
1
2
3
RegistryKey r = new RegistryKey(RootKey.HKEY_CURRENT_USER, "Software//BEQ
Technologies");
r.create();

3.写入字符串值

?
1
2
3
RegistryKey r = new RegistryKey(RootKey.HKEY_CURRENT_USER, "Software//BEQ Technologies");
RegistryValue v = new RegistryValue("myVal", ValueType.REG_SZ, "data");
r.setValue(v);

4.获取DWORD值

?
1
2
3
4
5
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.选择文件夹对话框

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/*
import java.io.*;
import javax.swing.*;
*/
JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new File("."));
chooser.setFileFilter(new javax.swing.filechooser.FileFilter() {
public boolean accept(File f) {
return f.getName().toLowerCase().endsWith(".gif")
|| f.isDirectory();
}
public String getDescription() {
return "GIF Images";
}
});
int r = chooser.showOpenDialog(null);
if (r == JFileChooser.APPROVE_OPTION) {
String name = chooser.getSelectedFile().getPath();
// label.setIcon(new ImageIcon(name));
}

54.删除空文件夹

?
1
2
3
4
5
6
7
8
9
10
//import java.io.*;
File f=new File(%%1);
if (isFolerNull(f)) {
for (File file :f.listFiles()) {
if (file.list().length == 0) {
System.out.println(file.getPath());
file.delete();
}
}
}

55.发送数据到剪贴板

?
1
2
3
4
5
//import java.awt.*;
//import java.awt.datatransfer.*;
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
Transferable tText = new StringSelection(%%1);
clipboard.setContents(tText, null);

56.从剪贴板中取数据

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//import java.awt.*;
//import java.awt.datatransfer.*;
// 取得系统剪贴板里可传输的数据构造的Java对象
Transferable t = Toolkit.getDefaultToolkit()
.getSystemClipboard().getContents(null);
try {
if (t != null
&& t.isDataFlavorSupported(DataFlavor.stringFlavor)) {
// 因为原系的剪贴板里有多种信息, 如文字, 图片, 文件等
// 先判断开始取得的可传输的数据是不是文字, 如果是, 取得这些文字
String s = (String) t
.getTransferData(DataFlavor.stringFlavor);
// 同样, 因为Transferable中的DataFlavor是多种类型的,
// 所以传入DataFlavor这个参数, 指定要取得哪种类型的Data.
System.out.println(s);
}
} catch (UnsupportedFlavorException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}

57.获取文件路径的父路径

复制代码 代码如下:
String %%2=%%1.substring(0,%%1.lastIndexOf("//"));

58.创建快捷方式

 

?
1
2
3
4
5
6
7
8
9
//import java.io.*;
try {
PrintWriter pw=new PrintWriter(new FileOutputStream("C:/a.bat"));
pw.println(%%1);"C:/a.txt"
pw.close();
}
catch(IOException e){
e.printStackTrace();
}

59.弹出快捷菜单

?
1
2
3
//MouseEvent e
JPopupMenu jpm=new JPopupMenu();
show(jpm,x,y);

60.文件夹复制到整合操作

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/*
import java.io.*;
import java.util.*;
import javax.swing.*;
*/
JFileChooser Jfc = new JFileChooser("请选择源路径"); // 建立选择档案对话
//方块盒 Jfc
if (!Jfc.isFileSelectionEnabled()) {
return;
}
String %%1 = Jfc.getSelectedFile().getParent();
Jfc = new JFileChooser("请选择目标路径"); // 建立选择档案对话方块盒 Jfc
if (!Jfc.isFileSelectionEnabled()) {
return;
}
String %%2 = Jfc.getSelectedFile().getParent();
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(
folderList2.peek() + File.separator
+ (temp.getName()).toString());
byte[] b = new byte[5120];
int len;
while ((len = input.read(b)) != -1) {
output.write(b, 0, len);
}
output.flush();
output.close();
input.close();
}
if (temp.isDirectory()) {// 如果是子文件夹
for (File f : temp.listFiles()) {
if (f.isDirectory()) {
folderList.add(f.getPath());
folderList2.add(folderList2.peek()
+ File.separator + f.getName());
}
}
}
}
} catch (Exception e) {
//System.out.println("复制整个文件夹内容操作出错");
e.printStackTrace();
}
folderList.removeFirst();
folderList2.removeFirst();
}

61.文件夹移动到整合操作

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
/*
import java.io.*;
import java.util.*;
import javax.swing.*;
*/
JFileChooser Jfc = new JFileChooser("请选择源路径"); // 建立选择档案对话
//方块盒 Jfc
if (!Jfc.isFileSelectionEnabled()) {
return;
}
String %%1 = Jfc.getSelectedFile().getParent();
Jfc = new JFileChooser("请选择目标路径"); // 建立选择档案对话方块盒 Jfc
if (!Jfc.isFileSelectionEnabled()) {
return;
}
String %%2 = Jfc.getSelectedFile().getParent();

62.目录下所有文件夹复制到整合操作

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/*
import java.io.*;
import java.util.*;
import javax.swing.*;
*/
JFileChooser Jfc = new JFileChooser("请选择源路径");
// 建立选择档案对话
//方块盒 Jfc
if (!Jfc.isFileSelectionEnabled()) {
return;
}
String %%1 = Jfc.getSelectedFile().getParent();
Jfc = new JFileChooser("请选择目标路径"); // 建立选择档案对话方块盒 Jfc
if (!Jfc.isFileSelectionEnabled()) {
return;
}
String %%2 = Jfc.getSelectedFile().getParent();

63.目录下所有文件夹移动到整合操作

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/*
import java.io.*;
import java.util.*;
import javax.swing.*;
*/
JFileChooser Jfc = new JFileChooser("请选择源路径");
// 建立选择档案对话
//方块盒 Jfc
if (!Jfc.isFileSelectionEnabled()) {
return;
}
String %%1 = Jfc.getSelectedFile().getParent();
Jfc = new JFileChooser("请选择目标路径");
// 建立选择档案对话方块盒 Jfc
if (!Jfc.isFileSelectionEnabled()) {
return;
}
String %%2 = Jfc.getSelectedFile().getParent();

64.目录下所有文件复制到整合操作

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/*
import java.io.*;
import java.util.*;
import javax.swing.*;
*/
JFileChooser Jfc = new JFileChooser("请选择源路径");
// 建立选择档案对话
//方块盒 Jfc
if (!Jfc.isFileSelectionEnabled()) {
return;
}
String %%1 = Jfc.getSelectedFile().getParent();
Jfc = new JFileChooser("请选择目标路径");
// 建立选择档案对话方块盒 Jfc
if (!Jfc.isFileSelectionEnabled()) {
return;
}
String %%2 = Jfc.getSelectedFile().getParent();

65.目录下所有文件移动到整合操作

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/*
import java.io.*;
import java.util.*;
import javax.swing.*;
*/
JFileChooser Jfc = new JFileChooser("请选择源路径");
// 建立选择档案对话
//方块盒 Jfc
if (!Jfc.isFileSelectionEnabled()) {
return;
}
String %%1 = Jfc.getSelectedFile().getParent();
Jfc = new JFileChooser("请选择目标路径");
// 建立选择档案对话方块盒 Jfc
if (!Jfc.isFileSelectionEnabled()) {
return;
}
String %%2 = Jfc.getSelectedFile().getParent();

66.对目标压缩文件解压缩到指定文件夹

?
1
2
3
4
5
/*
import java.io.*;
import java.util.*;
import javax.swing.*;
*/

67.创建目录副本整合操作

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/*
import java.io.*;
import java.util.*;
import javax.swing.*;
*/
JFileChooser Jfc = new JFileChooser("请选择源路径");
// 建立选择档案对话
方块盒 Jfc
if (!Jfc.isFileSelectionEnabled()) {
return;
}
String %%1 = Jfc.getSelectedFile().getParent();
Jfc = new JFileChooser("请选择目标路径");
// 建立选择档案对话方块盒 Jfc
if (!Jfc.isFileSelectionEnabled()) {
return;
}
String %%2 = Jfc.getSelectedFile().getParent();

68.打开网页

?
1
2
3
4
5
6
7
//import java.io.*;
try{
String command = "C://Program Files//Internet Explorer//Iexplore.exe "+%%1;
Runtime.getRuntime().exec(command);
} catch (IOException ex) {
ex.printStackTrace();
}

69.删除空文件夹整合操作

?
1
2
3
4
5
/*
import java.io.*;
import java.util.*;
import javax.swing.*;
*/

70.获取磁盘所有分区后再把光驱盘符去除(用"/0"代替),把结果放在数组allfenqu[] 中,数组中每
个元素代表一个分区盘符,不包括 :// 这样的路径,allfenqu[]数组开始时存放的是所有盘符。 
当我用这样的代码测试结果是正确的,光驱盘符会被去掉:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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.激活一个程序或程序关联的文件

?
1
2
3
4
5
6
//import java.io.*;
try {
Runtime.getRuntime().exec(%%1);
} catch (IOException e) {
e.printStackTrace();
}

72.HTTP下载

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
public class DownloadCSVFileAction extends Action{
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception {
try {
String fileName = request.getParameter( "fileName ");
long maID = Long.parseLong(request.getParameter( "maID "));
String filePath = request.getSession().getServletContext
().getRealPath( "/ ")+ "csv/ "+maID+ "/ "+fileName;
File fdown = new File(filePath);
int filelength = Integer.parseInt(String.valueOf
(fdown.length()));
//下载类型
response.setContentType( "application/text;charset=GB2312 ");
response.setHeader( "Content-Dispositon ", "attachment;filename=
销售详细记录.csv "); //销售详细记录.csv是我想要的下载文件的文件名,但是下载对话框中显
示的是 downLoadCSVFile.do
response.setContentLength(filelength);
byte b[]=new byte[filelength];
FileInputStream fi=new FileInputStream(fdown);
OutputStream o=response.getOutputStream();
int n = 0;
while((n=fi.read(b))!=-1) {
o.write(b,0,n);
}
fi.close();
o.close();
return null;
}catch (Exception e) {
request.setAttribute( "ERROR ", e);
return mapping.findForward( "error ");
}
}
}

对应的下载类型

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
private String getContentType(String fileName) {
String fileNameTmp = fileName.toLowerCase();
String ret = "";
if (fileNameTmp.endsWith("txt")) {
ret = "text/plain";
}
if (fileNameTmp.endsWith("gif")) {
ret = "image/gif";
}
if (fileNameTmp.endsWith("jpg")) {
ret = "image/jpeg";
}
if (fileNameTmp.endsWith("jpeg")) {
ret = "image/jpeg";
}
if (fileNameTmp.endsWith("jpe")) {
ret = "image/jpeg";
}
if (fileNameTmp.endsWith("zip")) {
ret = "application/zip";
}
if (fileNameTmp.endsWith("rar")) {
ret = "application/rar";
}
if (fileNameTmp.endsWith("doc")) {
ret = "application/msword";
}
if (fileNameTmp.endsWith("ppt")) {
ret = "application/vnd.ms-powerpoint";
}
if (fileNameTmp.endsWith("xls")) {
ret = "application/vnd.ms-excel";
}
if (fileNameTmp.endsWith("html")) {
ret = "text/html";
}
if (fileNameTmp.endsWith("htm")) {
ret = "text/html";
}
if (fileNameTmp.endsWith("tif")) {
ret = "image/tiff";
}
if (fileNameTmp.endsWith("tiff")) {
ret = "image/tiff";
}
if (fileNameTmp.endsWith("pdf")) {
ret = "application/pdf";
}
return ret;
}

73.FTP下载

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/*
import sun.net.ftp.FtpClient;
import java.io.*;
import sun.net.*;
*/
//如果文件在某个目录下,则加入fc.cd("foodir");
//比如要下载ftp://ftp.xx.com/index.html则:
try
{
FtpClient fc=new FtpClient("ftp.xx.com");
fc.login("username","888888");
int ch;
File fi = new File("c://index.html");
RandomAccessFile getFile = new RandomAccessFile(fi,"rw");
getFile.seek(0);
TelnetInputStream fget=fc.get("index.html");
DataInputStream puts = new DataInputStream(fget);
while ((ch = puts.read()) >= 0) {
getFile.write(ch);
}
fget.close();
getFile.close();
fc.closeServer();
}
catch (IOException ex)
{
ex.printStackTrace();
}

74.写图像到剪切板 setClipboardImage

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/*
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.删除文件夹下的所有文件且不删除文件夹下的文件夹

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//import java.io.*;
//import java.util.*;
LinkedList<String> folderList = new LinkedList<String>();
folderList.add(%%1);
while (folderList.size() > 0) {
File file = new File(folderList.peek());
folderList.removeLast();
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();
}
}

希望本文所述对大家Java程序设计有所帮助。

延伸 · 阅读

精彩推荐