`
nudtgk2000
  • 浏览: 72994 次
  • 性别: Icon_minigender_1
  • 来自: 大连
社区版块
存档分类
最新评论

【转载】java 文件操作大全(1)

阅读更多
所有代码转载时未经测试
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) {  
    /*TO ADD CODE*/
    %%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 
                    if (temp.isDirectory()) {    //如果是子文件夹 
                        folderList.add(folderList.get(j) + "/" + file[i]); 
                        folderList2.add(folderList2.get(j) + "/" + file[i]); 
                    } 
                }//for 
            } catch (Exception e) { 
                System.out.println("复制整个文件夹内容操作出错"); 
                e.printStackTrace(); 
            } 
        }//for 
    }//if
}//for

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 
            if (temp.isDirectory()) {// 如果是子文件夹 
                for (File f : temp.listFiles()) { 
                    if (f.isDirectory()) { 
                        folderList.add(f.getPath()); 
                        folderList2.add(folderList2.peek()
                                      + File.separator
                                      + f.getName()); 
                    } 
                } 
            } 
        }//for 
    } catch (Exception e) { 
        // System.out.println("复制整个文件夹内容操作出错"); 
        e.printStackTrace(); 
    } 
    folderList.removeFirst(); 
    folderList2.removeFirst(); 
}//while 
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 
                    if (temp.isDirectory()) {//如果是子文件夹 
                        folderList.add(folderList.get(j) + "/" + file[i]); 
                        folderList2.add(folderList2.get(j) + "/" + file[i]); 
                    } 
                }//for 
            } catch (Exception e) { 
                System.out.println("复制整个文件夹内容操作出错"); 
                e.printStackTrace();
            } 
        }//try 
        movefoldersList[k].delete(); 
    }//if 
}//for

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]); 
            } 
        }//for 
    } catch (Exception e) { 
        System.out.println("复制整个文件夹内容操作出错"); 
        e.printStackTrace(); 
    } 
}//for

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

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

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] = ""; 
                    } 
                }//else 
                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++; 
                } 
            }//if 
        }//while 
        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(); 
        } 
    } 
}//if

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] = ""; 
                    } 
                }//else 
                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++; 
                } 
            }//if 
        }//while 
        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(); 
        } 
    } 
}//if

转载自http://tieba.baidu.com/f?kz=585908932
另有一篇http://andyone.iteye.com/blog/316990
分享到:
评论

相关推荐

    java文件操作大全

    如何在Java中操作文件呢?转载供大家欣赏

    java文件路径操作详细(转载)

    Java文件路径操作是Java开发中常见且重要的任务,无论是在读写文件、处理资源还是进行系统交互时,都需要对文件路径进行操作。本篇将详细探讨Java中的文件路径处理技术,主要涵盖以下知识点: 1. **File类**: ...

    JAVA数据库连接大全-转载

    这篇博客"JAVA数据库连接大全-转载"可能详细介绍了在Java中如何管理和使用数据库连接,包括使用JDBC API,数据库连接池以及相关的工具。这里我们将深入探讨JDBC、数据库连接池的重要性和配置方法。 1. **JDBC基础**...

    Java字节码(.class文件)格式详解((转载)

    每个Java类都由一个`.class`文件表示,其中包含了编译后的字节码指令。`.class`文件的结构非常严谨,它不仅包含了类的信息,如类名、方法、变量等,还包含了运行时必要的元数据。 一、`.class`文件结构 1. 文件头:...

    java多线程扫描器(转载)

    ### Java多线程扫描器:实现对任意主机端口的扫描 #### 一、系统功能与设计要点 **1.1 设计任务与要求** Java多线程扫描器的开发旨在深化对Java面向对象程序设计的理解,特别是巩固Java语言的语法规范。此项目的...

    2008十大优秀Java应用程序(转载)

    ThinkFree使用Java编写,因此可以在多个操作系统上运行,同时提供在线版本,支持协作和多种文件格式处理。 这些Java应用程序的多样性表明,无论是在嵌入式系统、3D图形、Web开发、多媒体处理还是办公应用,Java都能...

    转载-Java语言入门教程

    这个教程假设读者对编程没有预先的知识,但需要有一定的计算机操作基础,例如文件管理。此外,教程特别指出,无论年龄大小,只要有学习的愿望,都能从Java编程中受益。 首先,计算机程序是由一系列指令组成的,这些...

    java语言整合API接口自动化测试框架

    MyFileUtils.java ##文件的操作类 Out.java ##重新封装了System.out.println()方法,打印当前的时间 TaskModel.java ##创建本次API测试的任务 TestApi.java ##执行测试 TimeUtils.java ##操作时间的...

    java 时间转换(转载)

    在提供的`Test.java`文件中,可能包含了对上述知识点的实际应用代码。通过阅读和理解这段代码,你可以更深入地了解Java中的时间转换操作。不过,由于实际代码没有给出,我们只能基于一般情况来讨论这些概念。在实际...

    深入分析 Java I/O 的工作机制(转载)

    内存映射文件(Memory-Mapped File)将文件映射到虚拟内存,使得文件操作如同访问内存一样快速。 10. **字符集编码** Java I/O系统广泛涉及字符编码,如ASCII、UTF-8、GBK等。Charset类提供了字符集的相关操作,...

    JAVA计算机管理系统

    4. j-jdbc - 这个文件名暗示了与Java JDBC(Java Database Connectivity)有关,JDBC是Java访问数据库的标准接口,用于连接和操作数据库,可能是数据库驱动配置文件,或者包含了数据库操作的示例代码。 综合以上...

    MANIFEST.MF 文件内容详解(转)

    这篇博文可能是从其他来源转载的,用于解释这个关键文件的结构和用途。 在Java开发中,MANIFEST.MF文件是每个JAR文件必须包含的文本文件,它定义了程序的主要属性,如主类(Main-Class),版本信息,依赖库等。以下...

    my1(java基础+页面设计)

    【标题】"my1(java基础+页面设计)"涵盖了两个主要的知识领域:Java基础和页面设计。这是一套学习资源,包括课件、实例、练习、答案以及开发工具的使用指南,旨在帮助初学者掌握Java编程语言的基础知识以及如何在实际...

    java+Web审批流程.rar

    在【压缩包子文件的文件名称列表】中提到的"java+Web审批流程(转载)"可能是项目的源代码文件、文档或者部署指南。这些文件可能包含以下部分: 1. **源代码**:包括Java源文件(.java),可能分布在不同的包结构下...

    java事例集合1

    【描述】中的"事例集合1(转载)"表明这些内容可能来源于网络,可能是某个开发者或教育者收集并整理的Java编程实例,目的是帮助学习者通过实际操作来理解Java编程。而"看韩剧www.pigkrtv.com"这部分看起来像是无关的...

    Java利用Preferences设置个人偏好,转载自:燕窝

    1. **Preferences API的基本操作**: - **创建节点**:你可以通过调用`Preferences.root()`获取顶级节点,然后使用`node(String nodeName)`方法创建新的子节点。 - **设置键值对**:使用`put(String key, String ...

    java编程事项(转载收集整理版)

    6. **输入/输出(I/O)**:Java的I/O流系统包括字符流和字节流,以及用于文件操作、网络通信和对象序列化的API。学会使用BufferedReader、FileWriter等类进行文件操作,是开发中常见的需求。 7. **网络编程**:Java...

    java开发html转pdf示例(转载)

    1. 右键点击项目 -&gt; Build Path -&gt; Configure Build Path -&gt; Libraries -&gt; Add Jars 或 Add External Jars,然后选择下载的jar文件。 接下来,我们将编写一个简单的Java程序来演示HTML转PDF的过程。以下是一个基本...

Global site tag (gtag.js) - Google Analytics