一、BufferedReader和BufferedWriter
高效的字符流
BufferedReader从字符输入流中读取文本,缓冲各个字符,从而实现字符。数组和行的高效读取
BufferedReader reader = new BufferedReader(new FileReader("a.txt"));
BufferedWriter writer = new BufferedWriter(new FileWriter("aa.txt"));
//可以指定缓冲区的大小,也可以使用默认的大小
char[] chars = new char[1024];
int len=0;
while((len=reader.read(chars))!=-1){
writer.write(chars,0,len);
writer.flush();
}
reader.close();
writer.close();
BufferedReader它有一个特殊的方法,readLine()一次读取一行内容
BufferedReader reader = new BufferedReader(new FileReader("MyTest3.java"));
//读取一行,写出一行来复制
BufferedWriter writer = new BufferedWriter(new FileWriter("Test.java"));
String line=null;
//BufferedReader有一个特殊的方法,一次读取一行
while ((line=reader.readLine())!=null){
writer.write(line);
writer.newLine();//换行符
}
reader.close();
writer.close();
二、案例演示
- 需求:把ArrayList集合中的字符串数据存储到文本文件
ArrayList<String> list = new ArrayList<>();
list.add("张艺");
list.add("梨儿");
list.add("姗姗");
list.add("思思");
list.add("王五");
BufferedWriter writer = new BufferedWriter(new FileWriter("cc.txt"));
for (String s : list) {
writer.write(s);
writer.newLine();
writer.flush();
}
writer.close();
- 需求:从文本文件中读取数据(每一行为一个字符串数据) 到集合中,并遍历集合
ArrayList<String> list = new ArrayList<>();
BufferedReader reader = new BufferedReader(new FileReader("cc.txt"));
String str=null;
while((str=reader.readLine())!=null){
list.add(str);
}
reader.close();
for (String s : list) {
System.out.println(s);
}
- 需求:我有一个文本文件,每一行是一个学生的名字,请写一个程序,每次允许随机获取一个学生名称
ArrayList<String> list = new ArrayList<>();
BufferedReader reader = new BufferedReader(new FileReader("Student.txt"));
String str=null;
while((str=reader.readLine())!=null){
list.add(str);
}
reader.close();
Random random = new Random();
int index = random.nextInt(list.size());
String s = list.get(index);
System.out.println(s);
- Scanner类
Scanner scanner = new Scanner(new File("a.txt"));//构建一个Scanner对象,它生成的值是从指定文件中扫描的
while(scanner.hasNextLine()){
//与BufferedReader和BufferedWriter一样,也是读一行写一行
String s = scanner.nextLine();
System.out.println(s);
}
Scanner scanner = new Scanner(new FileInputStream("a.txt"));//构建一个scanner对象,它生成的值是从指定的输入流中扫描的
while(scanner.hasNextLine()){
String s = scanner.nextLine();
System.out.println(s);
}
//Scanner scanner = new Scanner(System.in);//从键盘录入数据
InputStream in = System.in;//in关联的是键盘
Scanner scanner = new Scanner(in);
- 复制文件夹
public static void main(String[] args) throws IOException {
File srcFile = new File("E:\\音乐");
File targetFile = new File("D:\\" + srcFile.getName());
if(!targetFile.exists()){
targetFile.mkdirs();
}
copyFolder(srcFile,targetFile);
}
private static void copyFolder(File srcFile,File targetFile) throws IOException {
File[] files = srcFile.listFiles();
for (File f : files) {
if(f.isFile()){
copyFile(f,targetFile);
}else{
File file = new File(targetFile, f.getName());
if(!file.exists()){
file.mkdirs();
}
copyFolder(f,file);
}
}
}
private static void copyFile(File f,File targetFile) throws IOException {
FileInputStream in = new FileInputStream(f);
File newFile = new File(targetFile, f.getName());
FileOutputStream out = new FileOutputStream(newFile);
byte[] bytes = new byte[1024 * 8];
int len=0;
while((len=in.read(bytes))!=-1){
out.write(bytes,0,len);
out.flush();
}
in.close();
out.close();
}
- 复制文件夹并改名
复制D:\demo目录下所有文件到E:\demo.并且将其后缀名以.png结尾的更改为.jpg
public static void main(String[] args) throws IOException {
File srcFile = new File("D:\\demo");
File targetFile = new File("E:\\" + srcFile.getName());
if(!targetFile.exists()){
targetFile.mkdirs();
}
copyFolder(srcFile,targetFile);
}
private static void copyFolder(File srcFile,File targetFile) throws IOException {
File[] files = srcFile.listFiles();
for (File f : files) {
if(f.isFile()){
copyFile(f,targetFile);
}else{
File file = new File(targetFile, f.getName());
if(!file.exists()){
file.mkdirs();
}
copyFolder(f,file);
}
}
}
private static void copyFile(File f,File targetFile) throws IOException {
FileInputStream in = new FileInputStream(f);
String name = f.getName();
if(name.endsWith(".png")){
name=name.replace(".png",".jpg");
}
File newFile = new File(targetFile, name);
FileOutputStream out = new FileOutputStream(newFile);
byte[] bytes = new byte[1024 * 8];
int len=0;
while((len=in.read(bytes))!=-1){
out.write(bytes,0,len);
out.flush();
}
in.close();
out.close();
}
- 需求:键盘录入3个学生信息(姓名, 语文成绩(chineseScore),数学成绩(mathScore), 英语成绩(englishScore)), 按照总分从高到低存入文本文件
public static void main(String[] args) throws IOException {
TreeSet<Student> treeSet = new TreeSet<>(new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
int i = s1.getTotalScore() - s2.getTotalScore();
int i1 = i == 0 ? s1.getName().compareTo(s2.getName()) : i;
return -i1;
}
});
for (int i = 1; i <= 3; i++) {
Student student = new Student();
Scanner scanner = new Scanner(System.in);
System.out.println("请输入第"+i+"个学生姓名");
String name = scanner.nextLine();
student.setName(name);
System.out.println("请输入第"+i+"个学生的语文成绩");
int yw = scanner.nextInt();
student.setChineseScore(yw);
System.out.println("请输入第"+i+"个学生的数学成绩");
int sx = scanner.nextInt();
student.setMathScore(sx);
System.out.println("请输入第"+i+"个学生的英语成绩");
int yy = scanner.nextInt();
student.setEnglishScore(yy);
treeSet.add(student);
}
BufferedWriter writer = new BufferedWriter(new FileWriter("student.txt"));
writer.write("序号"+"\t"+"姓名"+"\t"+"语文"+"\t"+"数学"+"\t"+"英语"+"\t"+"总分");
writer.flush();
writer.newLine();
int index=1;
for (Student student : treeSet) {
writer.write(index+"\t"+student.getName()+"\t"+student.getChineseScore()+"\t"+student.getMathScore()+"\t"+student.getEnglishScore()+"\t"+student.getTotalScore());
writer.flush();
writer.newLine();
index++;
}
writer.close();
}
三、数据输入输出流
DataInputStream和DataOutputStream
数据输入输出流的特点:能够读写基本数据类型
DataOutputStream out = new DataOutputStream(new FileOutputStream("b.txt"));
out.writeBoolean(false);
out.writeUTF("你好");
out.writeDouble(3.14);
out.writeInt(100);
out.close();
DataInputStream in = new DataInputStream(new FileInputStream("b.txt"));
//怎么写的就怎么读,顺序不要乱
boolean b = in.readBoolean();
String s = in.readUTF();
double v = in.readDouble();
int i = in.readInt();
in.close();
四、内存操作流
内存操作流,不关联文件,只是内存对数据进行读写
1.操作字节数组(ByteArrayInputStream和ByteArrayOutputStream)
ByteArrayOutputStream此类实现了一个输出流,其中的数据被写入byte数组,缓冲区会随着数据的写入不断增强。可使用toByteArray()和toString()获取数据
//关闭此流无效,此类中的方法在关闭流后仍可被调用
ByteArrayOutputStream out = new ByteArrayOutputStream();
//写数据
out.write("横眉冷对".getBytes());
out.write("俯首甘为".getBytes());
//取出缓冲区的数据
byte[] allBytes = out.toByteArray();
String s = new String(allBytes);
System.out.println(s);
// 取出缓冲区的数据
// String s1 = out.toString();
// System.out.println(s1);
ByteArrayInputStream in = new ByteArrayInputStream(allBytes);
byte[] bytes = new byte[1024 * 8];
int len=in.read(bytes);
String s1 = new String(bytes, 0, len);
System.out.println(s1);
2.操作字符数组(CharArrayReader和CharArrayWrite)
CharArrayWriter writer = new CharArrayWriter();
writer.write("abc");
writer.write("abc");
writer.write("abc");
//取出缓冲区里的数据
char[] chars = writer.toCharArray();
System.out.println(String.valueOf(chars));
System.out.println(writer.toString());
3.操作字符串(StringReader和StringWriter)
StringWriter writer = new StringWriter();
writer.write("abc");
writer.append("abc");
System.out.println(writer.toString());
五、打印流
打印流:只操作目的地,不关联源文件
1.字节打印流PrintStream
PrintStream printStream = new PrintStream(new FileOutputStream("b.txt"));
printStream.write("字节打印流".getBytes());
printStream.print(true);
printStream.print(100);
printStream.close();
PrintStream out = System.out;
out.write("abc".getBytes());
out.print(3.14);
System.out.println("abc");
2.字符打印流
//参数2:true自动刷新
//如果启用了自动刷新,则只有在调用println、printf 或 format 的其中一个方法时才可能完成此操作
PrintWriter writer = new PrintWriter(new FileOutputStream("b.txt",true));
writer.write("字符打印流");
writer.println("abc");
writer.println("abc");
writer.println("abc");
writer.println("abc");
writer.flush();
writer.close();
案例演示
- 把多个文件合成一个文件
public static void main(String[] args) throws IOException {
FileInputStream in1 = new FileInputStream("许巍 - 曾经的你.mp3");
FileInputStream in2 = new FileInputStream("辛晓琪 - 领悟.mp3");
FileOutputStream out = new FileOutputStream("歌曲串烧");
ArrayList<FileInputStream> list = new ArrayList<>();
list.add(in1);
list.add(in2);
byte[] bytes = new byte[1024 * 8];
int len=0;
for (FileInputStream in : list) {
while((len=in.read(bytes))!=-1){
out.write(bytes,0,len);
out.flush();
}
in.close();
}
out.close();
}
- 打印流复制文本文件
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader("test.java"));
PrintWriter printWriter = new PrintWriter(new FileOutputStream("aa.java"), true);
String line=null;
while((line=reader.readLine())!=null){
printWriter.println(line);
}
reader.close();
printWriter.close();
}
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(new File("test.java"));
PrintWriter printWriter = new PrintWriter(new FileOutputStream("bb.java"));
while(scanner.hasNextLine()){
String s = scanner.nextLine();
printWriter.println(s);
}
scanner.close();
printWriter.close();
}
- 键盘录入的方式
//方式一
Scanner scanner = new Scanner(System.in);
System.out.println("请输入数据");
int i = scanner.nextInt();
System.out.println(i);
//方式二
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.println("请输入字符串");
String s = reader.readLine();
System.out.println(s);