文件字符字节流操作
下面主要讲解文件的字符字节的各种操作相应代码实现
一.文件字节流
1.文件字节输入流
public static void FileInfo() {
try {
FileInputStream in = new FileInputStream("D:\\刷课\\abc\\tt1.txt");
byte[] b = new byte[1];
int len = 0;
while((len = in.read(b)) != -1) {
System.out.print(new String(b,0,len));
}
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
2.文件字节流输出流
public static void testFioeoutputStream() {
try {
FileOutputStream out = new FileOutputStream("D:\\\\刷课\\\\abc\\\\tt4.txt");
String str = "dawdagvawfgaw";
out.write(str.getBytes());
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
3.文件字节流的复制
public static void copyFile(String inPath, String outPath) {
try {
FileInputStream in = new FileInputStream(inPath);
FileOutputStream out = new FileOutputStream(outPath);
byte[] b = new byte[100];
int len = 0;
while((len = in.read(b)) != -1) {
out.write(b, 0, len);
}
out.flush();
out.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
二. 文件字符流
1.文件字符输入流
public static void testFileReader(String inPath) {//文件字符输入流
try {
FileReader fr = new FileReader(inPath); //创建文件字符输入流的对象
char[] c = new char[1000]; //创建临时存放数据的数组
int len = 0; //定义一个输入流的读取长度
while((len = fr.read(c))!=-1) {
System.out.println(new String(c, 0, len));
}
fr.close(); //关闭文件
} catch (Exception e) {
e.printStackTrace();
}
}
2.文件字符输出流
public static void testFileWriter(String text,String outPath) { //文件字符输出流
try {
FileWriter fw = new FileWriter(outPath);
fw.write(text); //将text写到内存
fw.flush(); //将内存的数据刷到硬盘
fw.close(); //关闭流
} catch (Exception e) {
e.printStackTrace();
}
}
3.文件字符的复制
//字符流拷贝文件,inPath为需要拷贝的文件地址 outPath为拷贝后存入的文件地址
public static void copyFile(String inPath, String outPath) {
try {
FileReader fr = new FileReader(inPath);
FileWriter fw = new FileWriter(outPath);
char[] c = new char[100];
int len = 0;
while((len = fr.read(c)) != -1){ //读取数据
fw.write(c, 0, len); //写入数据到内存
}
fw.flush();
fr.close();
fw.close();
} catch (Exception e) {
e.printStackTrace();
}
}