用字符流读取文件并打印
//文件读取(字符流)
public static void readStream() {
String path = "G:\\wjfz.txt";//文件位置
File file = new File(path);
try {
FileInputStream fileInputStream = new FileInputStream(file);
byte[] bytes = new byte[100];
int num = 0;
while ((num = fileInputStream.read(bytes)) != -1) {
String s = new String(bytes, 0, num);
System.out.println(s);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
用字符流复制文件
//文件复制(字符流)
public static void copyStream() {
String path = "C:\\Users\\xlz\\Desktop\\71ac2d26-45042d7.png";//文件位置
String copyPath = "G:\\io\\";//复制到文件位置
String endName = path.substring(path.indexOf("."));//截取文件后缀名
String copyName = copyPath + UUID.randomUUID() + endName;//生成新的文件名称
try {
FileInputStream fileInputStream = new FileInputStream(path);
FileOutputStream fileOutputStream = new FileOutputStream(copyName);
int num = 0;
byte[] bytes = new byte[100];
while ((num = fileInputStream.read(bytes)) != -1) {
fileOutputStream.write(bytes, 0, num);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
用字符流文件复制(只能复制文本文件)
//文件复制(字节流)只能读取text文本文件
public static void copyReader(){
String path = "G:\\io\\111.txt";
String copyPath = "G:\\io\\";
String name = copyPath+UUID.randomUUID()+".txt";
System.out.println(name);
try {
FileReader fileReader = new FileReader(path);
FileWriter fileWriter = new FileWriter(name);
int num = 0;
char[] chars = new char[10];
while ((num = fileReader.read(chars))!=-1){
fileWriter.write(chars,0,num);
}
fileWriter.flush();
fileReader.close();
fileWriter.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
文件复制用包装流进行包装复制(只能复制文本文件)
//文件复制用Stream和reader包装
public static void copyStreamReader(){
String path = "G:\\io\\111.txt";//文件位置
String endName = path.substring(path.indexOf("."));//文件名后缀
String copyPath = "G:\\io\\";//复制到哪里
String name = copyPath + UUID.randomUUID()+endName;//生成新的文件名
try {
FileInputStream fileInputStream = new FileInputStream(path);//字节流
InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);//字节流转成字符流
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);//字符流
FileOutputStream fileOutputStream = new FileOutputStream(name);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream);
BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
String s = null;
while ((s = bufferedReader.readLine())!=null){
bufferedWriter.write(s+"\n");
}
bufferedWriter.flush();
bufferedWriter.close();
bufferedReader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}