1、通用複制檔案photo.jpg(可以是任意格式的檔案)到指定目錄(如photoOpy.jpg)下:
//建立輸入流
FileInputStream reader=new FileInputStream("F:/photo.jpg");
//建立輸出流
FileOutputStream writer=new FileOutputStream(F:/photoCopy.jpg);
//定義讀的位元組數組大小
byte b[]=new byte[1024];
int length;
while((length=reader.read(b))!=-1){
//将資料寫入檔案
writer.write(b,0,length);
}
//關閉讀
reader.close();
//關閉寫
writer.close();
2、讀取txt檔案内容
(1)測試用位元組流轉字元流讀取txt檔案
@Test
public void testReadTxt() {
String filePath = "D:/qq.log";
List<Object> list = new ArrayList<Object>();
Object textContent = null;
try {
File file = new File(filePath);
if (file.isFile()) {
// 建立輸入流,讀取位元組檔案
FileInputStream fs = new FileInputStream(file);
// 建立轉換流,将位元組流轉換成字元流,預設編碼格式是GBK
InputStreamReader isr = new InputStreamReader(fs, "UTF-8");
// 建立緩沖流讀取
BufferedReader br = new BufferedReader(isr);
// 開始讀取資料
while ((textContent = br.readLine()) != null) {
list.add(textContent);
}
} else {
System.out.println("檔案不存在!");
}
// 周遊檔案内容
for (Object ob : list) {
System.out.println(ob);
}
} catch (Exception e) {
e.printStackTrace();
}
}(2)使用純字元流讀取txt檔案
@Test
public void testResadTxt2()throws Exception{
String path="F:/testFileWriter.txt";
FileReader fr=null;
BufferedReader br=null;
try{
//如果不寫new File()而直接寫path也可以,但是如果使用path,那麼會多一次判斷而花費時間!
// fr=new FileReader(path);
fr=new FileReader(new File(path));
br=new BufferedReader(fr);
while(br.readLine()!=null){
System.out.println(br.readLine());
}
}catch(Exception e){
e.printStackTrace();
}finally{
br.close();
fr.close();
}
}3、寫入txt檔案
@Test
public void writerTxt(){
String txtPath="D:/20151104qwer.log";
try{
FileWriter fw=new FileWriter(new File(txtPath),true);
BufferedWriter rw=new BufferedWriter(fw);
rw.write("hello world"+"\r\n");
rw.close();
fw.close();
}catch(Exception e){
e.printStackTrace();
}
}