字節流、字符流、文件流基本寫法

沒啥好說的,詳見下面代碼:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class IOTest {
private static final String URL="F:\read.txt";    
private static final String URL2 = "F:/writer.txt";



/**
* @param args
*/
public static void main(String[] args) throws FileNotFoundException {
// TODO Auto-generated method stub
//寫入文件流
//private static final String URL="F:\read.txt";    
File file = new File(URL);
// File newFile=new File(path);  
//    file.transferTo(newFile); 
//按行讀取文件
BufferedReader br  = null;
BufferedWriter bw =null;
try {
br  = new BufferedReader(new FileReader(file));
bw = new BufferedWriter(new FileWriter(URL2));
} catch (IOException e1) {

e1.printStackTrace();
}


String temp = "";
try {
while((temp = br.readLine())!=null){
System.out.print(temp);
bw.write(temp);

}
} catch (IOException e) {
e.printStackTrace();
}finally{
if(br !=null && bw !=null){
try {
br.close();
bw.close();


} catch (IOException e) {
  e.printStackTrace();
}
}
}
// 字節輸入流
File file1 = new File(URL);
InputStream is = new FileInputStream(file1);
OutputStream os = new FileOutputStream(URL2);

int temp1 ;
try {
while((temp1 =is.read())!=-1){
os.write(temp1);
System.out.println(temp1);
}
} catch (IOException e) {
e.printStackTrace();
}finally{
if(is !=null && os !=null){
try {
is.close();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}

}
//字符流文件讀取
File f2 = new File(URL);

FileReader reader = null;
FileWriter writer =null;


int temp2;
try {
reader = new FileReader(f2);
writer = new FileWriter(URL2);
while((temp2 = reader.read()) !=-1){
writer.write(temp2);

System.out.println(temp2);
}
} catch (IOException e) {
e.printStackTrace();
}finally{
if(reader !=null && writer !=null ){
try {
reader.close();
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}

 

}


}


發佈了34 篇原創文章 · 獲贊 7 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章