Java-节点流(或文件流)

134 阅读2分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第17天,点击查看活动详情

读取文件

1.建立一个流对象,将已存在的一个文件加载进流。

  • FileReader fr = new FileReader(new File(“Test.txt”)); 2.创建一个临时存放数据的数组。
  • char[] ch = new char[1024]; 3.调用流对象的读取方法将流中的数据读入到数组中。
  • fr.read(ch);
  1. 关闭资源。
  • fr.close();
FileReader fr = null;
try {
fr = new FileReader(new File("c:\\test.txt"));
char[] buf = new char[1024];
int len;
while ((len = fr.read(buf)) != -1) {
System.out.print(new String(buf, 0, len));
}
} catch (IOException e) {
System.out.println("read-Exception :" + e.getMessage());
} finally {
if (fr != null) {
try {
fr.close();
} catch (IOException e) {
System.out.println("close-Exception :" + e.getMessage());
}
}
}

写入文件

1.创建流对象,建立数据存放文件

  • FileWriter fw = new FileWriter(new File(“Test.txt”)); 2.调用流对象的写入方法,将数据写入流
  • fw.write(“atguigu-songhongkang”); 3.关闭流资源,并将流中的数据清空到文件中。
  • fw.close();
FileWriter fw = null;
try {
fw = new FileWriter(new File("Test.txt"));
fw.write("atguigu-songhongkang");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fw != null)
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}

注意点

  • 定义文件路径时,注意:可以用“/”或者“\”。
  • 在写入一个文件时,如果使用构造器FileOutputStream(file),则目录下有同名文件将被覆盖。
  • 如果使用构造器FileOutputStream(file,true),则目录下的同名文件不会被覆盖,在文件内容末尾追加内容。
  • 在读取文件时,必须保证该文件已存在,否则报异常。
  • 字节流操作字节,比如:.mp3,.avi,.rmvb,mp4,.jpg,.doc,.ppt
  • 字符流操作字符,只能操作普通文本文件。最常见的文本文件:.txt,.java,.c,.cpp 等语言的源代码。尤其注意.doc,excel,ppt这些不是文本文件。

复制文件

long start=System.currentTimeMillis();
String secPath="视频路径";
String destPath="视频复制路径";
copyFile(secPath,destPath);
long end=System.currentTimeMillis();
System.out.println("复制操作花费的时间为"+(end-start));