1. 程式人生 > >java檔案讀寫,

java檔案讀寫,

/**
 * 
 */
package com.struts2.other;


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @author Administrator
 * 
 */
public class WriteInText {


/**
* @param args
*/
public static void main(String[] args) {
try {
saveDataToFile("/conf/data.txt");
} catch (Exception e) {
e.printStackTrace();
}
}


/**
* 向指定路徑的檔案寫入data中的內容

* @param fileName
* @param string
* @throws IOException
*/
public static void saveDataToFile(String str) throws IOException {
File f = new File("d:/data/data.txt");
if (!f.exists()) {
createFile();
}
BufferedReader br = new BufferedReader(new FileReader(f));
BufferedWriter bw = new BufferedWriter(new FileWriter(f));
// String s="你用方法或者session標記的使用者名稱字和身份";
// bw = new java.io.BufferedWriter(new
// java.io.OutputStreamWriter(writerStream, "UTF-8"));
if (br.readLine() == null) {
// byte[] midbytes = str.getBytes("UTF8");
// String srt2 = new String(midbytes, "UTF-8");
bw.write(str);
br.close();
bw.flush();
bw.close();
}
}


/**

*/
public static void createFile() {


// path表示你所建立檔案的路徑
String path = "d:/data";
File f = new File(path);
if (!f.exists()) {
f.mkdirs();
}
// fileName表示你建立的檔名;為txt型別;
String fileName = "data.txt";
File file = new File(f, fileName);
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}


}


/**
* 以行為單位讀取檔案,常用於讀面向行的格式化檔案
*/
public  String readFileByLines(String fileName) {
File file = new File(fileName);
BufferedReader reader = null;
String data="";
try {
reader = new BufferedReader(new FileReader(file));
String tempString = null;
int line = 1;
// 一次讀入一行,直到讀入null為檔案結束
while ((tempString = reader.readLine()) != null) {
// 顯示行號
System.out.println(tempString);
data=tempString;
line++;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
return data;
}


/**
* 以字元為單位讀取檔案,常用於讀文字,數字等型別的檔案

* @param fileName
*/
public static void readFileByChars(String fileName) {
File file = new File(fileName);
Reader reader = null;
try {
// 一次讀多個字元
char[] tempchars = new char[30];
int charread = 0;
reader = new InputStreamReader(new FileInputStream(fileName));
// 讀入多個字元到字元陣列中,charread為一次讀取字元數
while ((charread = reader.read(tempchars)) != -1) {
// 同樣遮蔽掉\r不顯示
if ((charread == tempchars.length)
&& (tempchars[tempchars.length - 1] != ' ')) {
System.out.print(tempchars);
} else {
for (int i = 0; i < charread; i++) {
if (tempchars[i] == '\r') {
continue;
} else {
System.out.print(tempchars[i]);
}
}
}
}


} catch (Exception e1) {
e1.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
}

}

          

一.獲得控制檯使用者輸入的資訊

     public String getInputMessage() throws IOException...{
         System.out.println("請輸入您的命令∶");
         byte buffer[]=new byte[1024];
         int count=System.in.read(buffer);
         char[] ch=new char[count-2];//最後兩位為結束符,刪去不要
         for(int i=0;i<count-2;i++)
             ch[i]=(char)buffer[i];
         String str=new String(ch);
         return str;
     }
     可以返回使用者輸入的資訊,不足之處在於不支援中文輸入,有待進一步改進。

     二.複製檔案
     1.以檔案流的方式複製檔案

     public void copyFile(String src,String dest) throws IOException...{
         FileInputStream in=new FileInputStream(src);
         File file=new File(dest);
         if(!file.exists())
             file.createNewFile();
         FileOutputStream out=new FileOutputStream(file);
         int c;
         byte buffer[]=new byte[1024];
         while((c=in.read(buffer))!=-1)...{
             for(int i=0;i<c;i++)
                 out.write(buffer[i]);        
         }
         in.close();
         out.close();
     }
     該方法經過測試,支援中文處理,並且可以複製多種型別,比如txt,xml,jpg,doc等多種格式

     三.寫檔案

     1.利用PrintStream寫檔案


     public void PrintStreamDemo()...{
         try ...{
             FileOutputStream out=new FileOutputStream("D:/test.txt");
             PrintStream p=new PrintStream(out);
             for(int i=0;i<10;i++)
                 p.println("This is "+i+" line");
         } catch (FileNotFoundException e) ...{
             e.printStackTrace();
         }
     }
     2.利用StringBuffer寫檔案
public void StringBufferDemo() throws IOException......{
         File file=new File("/root/sms.log");
         if(!file.exists())
             file.createNewFile();
         FileOutputStream out=new FileOutputStream(file,true);        
         for(int i=0;i<10000;i++)......{
             StringBuffer sb=new StringBuffer();
             sb.append("這是第"+i+"行:前面介紹的各種方法都不關用,為什麼總是奇怪的問題 ");
             out.write(sb.toString().getBytes("utf-8"));
         }        
         out.close();
     }
     該方法可以設定使用何種編碼,有效解決中文問題。
四.檔案重新命名
    
     public void renameFile(String path,String oldname,String newname)...{
         if(!oldname.equals(newname))...{//新的檔名和以前檔名不同時,才有必要進行重新命名
             File oldfile=new File(path+"/"+oldname);