FileReader和FileWriter 處理字符流(文本文件)
1.讀取一個文件的內容
public void testFileReader() {
FileReader fr = null;
try {
File file = new File("oop.txt");
fr = new FileReader(file);
char[] c = new char[24];
int len;
while ((len = fr.read(c)) != -1) {
String str = new String(c, 0, len);
System.out.print(str);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
2.實現文本文件的複製(通過FileReader和FileWriter)
對於非文本文件(圖片、視頻) 只能使用字節流
public void testFileReaderWriter() {
FileReader fr = null;
FileWriter fw = null;
try {
File src = new File("oop.txt");
File dest = new File("oop");
fr = new FileReader(src);
fw = new FileWriter(dest);
char[] c= new char[24];
int len;
while ((len = fr.read(c)) != -1) {
fw.write(c, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fw != null) {
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fr != null) {
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
3.把一個圖片的內容寫入到新的文件
public void testBufferedInputOutputStream() {
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
File file1 = new File("one.jpg");
File file2 = new File("1.jpg");
FileInputStream fis= new FileInputStream(file1);
FileOutputStream fos = new FileOutputStream(file2);
bis = new BufferedInputStream(fis);
bos = new BufferedOutputStream(fos);
byte[] b = new byte[1024];
int len;
while ((len = bis.read(b)) != -1) {
bos.write(b, 0, len);
bos.flush();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
4.使用緩衝流實現文件複製
public void copyFile(String src,String dest) {
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
File file1 = new File(src);
File file2 = new File(dest);
FileInputStream fis= new FileInputStream(file1);
FileOutputStream fos = new FileOutputStream(file2);
bis = new BufferedInputStream(fis);
bos = new BufferedOutputStream(fos);
byte[] b = new byte[1024];
int len;
while ((len = bis.read(b)) != -1) {
bos.write(b, 0, len);
bos.flush();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}