IO流

对于流的描述,流是一种抽象的描述。

流的分类:

1、输入流(Input)

2、输出流(Output)

 

按类型分:

1、字节流(InputStream/OutputStream)

public class ReadFileByLoop {

public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub

// 根据给定的文件路径构建一个字节输入流对象
File f = new File("C:\\Users\\lenovo\\Desktop\\培训\\试卷及答案\\1.txt");
InputStream is = new FileInputStream(f);
// 准备一个自己缓冲区
byte[] b = new byte[1024];
// 申明一个临时变量记录本次读取的真实长度
int len = 0;
while ((len = is.read(b)) != -1) {
String s = new String(b, 0, len);
System.out.println(s);
}

// is.close();
}

}

 

2、字符流(Reader/Writer)


public class ReadFileByChar {

public static void main(String[] args) throws IOException {
//创建一个File对象
File f = new File("C:\\Users\\lenovo\\Desktop\\培训\\试卷及答案\\1.txt");
//构建一个字符输入流
FileReader fr = new FileReader(f);
char[] a=new char[1024];
int len;
while((len=fr.read(a))!=-1){
String s=new String(a,0,len);
System.out.println(s);
}
fr.close();
}
}

 

按照功能分:

1、节点流(低级流)

2、处理流(高级流)

字节流到字符流之间的流动用InputStreamReader

BufferedReader x=new BufferedReader(new InputStreamReader(System.in))

字符流到字符流之间的流动用OutputStreamWriter

 

 

对一个文件夹拷贝


public class Test {

// 递归方法
public static void copyFile(File file, File file2) {
// 当找到目录时,创建目录
if (file.isDirectory()) {
file2.mkdir(); // 创建目录
File[] files = file.listFiles();
for (File f : files) {
// 递归
copyFile(f, new File(file2, f.getName()));
}
// 当找到文件时
} else if (file.isFile()) {
File f = new File(file2.getAbsolutePath());
try {
f.createNewFile();
copyDatas(file.getAbsolutePath(), f.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
}
}

// 复制文件数据的方法
public static void copyDatas(String filePath, String filePath1) {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
// 字节流
fis = new FileInputStream(filePath);
fos = new FileOutputStream(filePath1);
byte[] buffer = new byte[1024];
while (true) {
int temp = fis.read(buffer, 0, buffer.length);
if (temp == -1) {
版权声明:本文为danhua520tuzi原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/danhua520tuzi/p/9392431.html