字节流和字符流的区别:
字节流就是可以读取图片,文本,视频等二进制数据;字符流只能读取纯文本文件。
字节流读写示例:
public static void main(String[] args) {
String path = "D:/study_project/1.jpg";
String path1 = "D:/study_project/2.jpg";
String path2 = "D:/study_project/java-io-test.txt";
String path3 = "D:/study_project/java-io-test-to.txt";
//readTxt(path2);
writeFile(path2,path3);
}
/**
* 文件的写入:
* @param fromPath 源
* @param toPath 目标
*/
public static void writeFile(String fromPath,String toPath) {
BufferedInputStream fis = null;
BufferedOutputStream fos = null;
int len = 2;
byte[] buffer = new byte[len];
try {
fis = new BufferedInputStream(new FileInputStream(fromPath));
fos = new BufferedOutputStream(new FileOutputStream(toPath));
while ((fis.read(buffer, 0, len)!=-1) && buffer.length > 0) {
fos.write(buffer, 0, buffer.length);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("文件没有找到");
} catch (IOException e) {
e.printStackTrace();
System.out.println("文件读取异常");
} finally {
try {
fis.close();
fos.close();
} catch (Exception e2) {
System.out.println(e2);
}
}
}
public static void main(String[] args) {
String path = "D:/study_project/1.jpg";
String path1 = "D:/study_project/2.jpg";
String path2 = "D:/study_project/java-io-test.txt";
String path3 = "D:/study_project/java-io-test-to.txt";
readChar(path2,path3);
}
public static void readChar(String fromPath,String toPath){
BufferedReader read = null;
BufferedWriter write = null;
int len = 20;
char[] buffer = new char[len];
try {
read = new BufferedReader(new InputStreamReader(new FileInputStream(fromPath), "utf8"));
write = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(toPath),"utf8"));
while ((read.read(buffer, 0, len)!=-1) && buffer.length > 0) {
write.write(buffer, 0, len);
}
write.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("文件没有找到");
} catch (IOException e) {
e.printStackTrace();
System.out.println("文件读取异常");
} finally {
try {
read.close();
write.close();
} catch (Exception e2) {
System.out.println(e2);
}
}
}