程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> Java最全文件操作實例匯總

Java最全文件操作實例匯總

編輯:關於JAVA

Java最全文件操作實例匯總。本站提示廣大學習愛好者:(Java最全文件操作實例匯總)文章只能為提供參考,不一定能成為您想要的結果。以下是Java最全文件操作實例匯總正文


本文實例匯總了Java文件操作。分享給年夜家供年夜家參考,詳細以下:

1.創立文件夾

//import java.io.*; 
File myFolderPath = new File(%%1); 
try { 
if (!myFolderPath.exists()) { 
myFolderPath.mkdir(); 
} 
} 
catch (Exception e) { 
System.out.println("新建目次操作失足"); 
e.printStackTrace(); 
}

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); 
resultFile.close(); 
} 
catch (Exception e) { 
System.out.println("新建文件操作失足"); 
e.printStackTrace(); 
}

3.刪除文件

//import java.io.*; 
File myDelFile = new File(%%1); 
try { 
myDelFile.delete(); 
} 
catch (Exception e) { 
System.out.println("刪除文件操作失足"); 
e.printStackTrace(); 
}

4.刪除文件夾

//import java.io.*; 
File delFolderPath = new File(%%1); 
try { 
delFolderPath.delete(); //刪除空文件夾 
} 
catch (Exception e) { 
System.out.println("刪除文件夾操作失足"); 
e.printStackTrace(); 
}

5.刪除一個文件下夾一切的文件夾

//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.清空文件夾

//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.讀取文件

//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.寫入文件

//import java.io.*; 
// 將數據寫入文件 
try { 
FileWriter fw = new FileWriter(%%1); 
fw.write(%%2); 
fw.flush(); 
fw.close(); 
} 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 b=filereadonly.setReadOnly(); 
} 
catch (Exception e) { 
System.out.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(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.復制文件夾

//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.復制一個文件夾下一切的文件夾到另外一個文件夾下

//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.挪動文件夾

//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.挪動一個文件夾下一切的文件夾到另外一個目次下

//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.以一個文件夾的框架在另外一個目次創立文件夾和空文件

//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.復制文件

//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.復制一個文件夾下一切的文件到另外一個目次

//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.調換擴大名

//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.*; 
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.挪動一個文件夾下一切文件到另外一個目次

//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.指定目次下搜刮文件

//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.翻開對話框

//import java.io.*; 
//import javax.swing.*; 
JFileChooser Jfc = new JFileChooser(); //樹立選擇檔案對話方塊盒 Jfc 
if (Jfc.isFileSelectionEnabled()) { 
File %%1 = 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) { 
System.out.print("using FileStreamDemo src des"); 
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.* 
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.文件簡略解密

//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文件屬性

//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文件屬性

//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.歸並一個文件下一切的文件

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文件屬性

//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數據庫

//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數據庫

//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緊縮文件

//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解緊縮

//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.遞歸刪除目次中的文件

//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 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

//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

//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

//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 ([email protected]) 
* @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.直接創立多級目次

//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(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.文本查找調換

//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(); 
}

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();

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值

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.選擇文件夾對話框

/* 
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.刪除空文件夾

//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.發送數據到剪貼板

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

56.從剪貼板中取數據

//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.創立快捷方法

//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.彈出快捷菜單

//MouseEvent e 
JPopupMenu jpm=new JPopupMenu();
show(jpm,x,y);

60.文件夾復制到整合操作

/* 
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.文件夾挪動到整合操作

/* 
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.目次下一切文件夾復制到整合操作

/* 
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.目次下一切文件夾挪動到整合操作

/* 
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.目次下一切文件復制到整合操作

/* 
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.目次下一切文件挪動到整合操作

/* 
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.對目的緊縮文件解緊縮到指定文件夾

/* 
import java.io.*; 
import java.util.*; 
import javax.swing.*; 
*/

67.創立目次正本整合操作

/* 
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.翻開網頁

//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.獲得磁盤一切分區後再把光驅盤符去除(用"/0"取代),把成果放在數組allfenqu[] 中,數組中每
個元素代表一個分區盤符,不包含 :// 如許的途徑,allfenqu[]數組開端時寄存的是一切盤符。 
當我用如許的代碼測試成果是准確的,光驅盤符會被去失落:

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.HTTP下載

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 "); 
} 
} 
}

對應的下載類型

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下載

/* 
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

/* 
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(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法式設計有所贊助。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved