java中缓冲流
程序员文章站
2024-03-06 23:53:14
...
BufferedReader:从字符输入流读取文本,缓冲字符,以提供字符,数组和行的高效读取
其构造方法如下
其部分方法如下
这里以读取a.txt中的两行数据为例
import java.io.*;
public class Main {
public static void main(String[] args) {
File file = new File("C:\\Users\\Administrator\\Desktop\\a.txt");
try {
Reader in = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(in);
String str;
while ((str = bufferedReader.readLine()) != null) {
System.out.println(str);
}
in.close();
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
BufferedWriter:将文本写入字符输出流,缓冲字符,以提供单个字符,数组和字符串的高效写入
其构造方法如下
其方法如下
这里以读取a.txt中的两行数据写入到b.txt为例
import java.io.*;
public class Main {
public static void main(String[] args) {
File file = new File("C:\\Users\\Administrator\\Desktop\\a.txt");
File file1 = new File("C:\\Users\\Administrator\\Desktop\\b.txt");
try {
Reader in = new FileReader(file);
Writer out = new FileWriter(file1);
BufferedReader bufferedReader = new BufferedReader(in);
BufferedWriter bufferedWriter = new BufferedWriter(out);
String str;
while ((str = bufferedReader.readLine()) != null) {
bufferedWriter.write(str);
bufferedWriter.newLine();
}
bufferedWriter.flush();
bufferedReader.close();
bufferedWriter.close();
in.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
下一篇: php使用变量动态创建类的对象用法示例