忽然发现 对文件基本操作有些生疏了,特此记录一些基本用法。
一:首先是基本定义的内容
- 这边的FilePathName也是可以不用这种指定的形式的,详细用法见 五。
String FileNamePath = "E:\\ideaWorkspace\\testStreamFileHere\\a.txt";
File file = new File(FileNamePath);
File file1 = new File("E:" + File.separator + "ideaWorkspace" + File.separator + "testStreamFileHere" + File.separator + "b.txt");
二:FileReader方式读取txt文件
FileReader fileReader = new FileReader(file);
char[] b = new char[1024];
int len = fileReader.read(b);
fileReader.close();
System.out.println("长度:"+len);
System.out.println(new String(b,0,len));
三:FileInputStream方式读取txt文件
InputStream inputStream = new FileInputStream(file);
byte[] b = new byte[1024];
int len = inputStream.read(b);
inputStream.close();
System.out.println("长度:"+len);
System.out.println(new String(b,0,len));
四:向已有文件后添加新的内容
try (
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file1.getCanonicalFile(), true));
BufferedReader reader = new BufferedReader(new FileReader(file1.getCanonicalFile()));
) {
bufferedWriter.write("我是增加的内容。");
String str;
while ((str = reader.readLine()) != null) {
System.out.println(str);
}
} catch (IOException e) {
System.err.println("操作失败!");
}
五:FileOutputStream方式复制文件,以及删除文件
File ff = null;
String rootPath = new File("").getCanonicalPath();
System.out.println("项目所在的路径:" + rootPath);
String txtName = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 8);
try (
FileInputStream inputStream = new FileInputStream(file);
FileOutputStream outputStream = new FileOutputStream(txtName + ".txt");
) {
int index = 0;
while ((index = inputStream.read()) != -1) {
outputStream.write(index);
}
System.out.println("模拟此处对文件进行其他操作========>");
} catch (Exception e) {
System.out.println("复制文件失败,操作失败!");
} finally {
System.out.println("操作结束,开始删除=========>");
try {
ff = new File(rootPath + File.separator + txtName + ".txt");
Files.delete(ff.toPath());
System.out.println("删除成功!" + ff.toPath().toString());
} catch (Exception e) {
System.out.println("删除失败!" + ff.toPath().toString());
}
System.out.println("=====================================补充几种获取路径的方式========================================");
System.out.println("第一种获取当前类所在工程路径:" + System.getProperty("user.dir"));
System.out.println("第二种获取用户主目录:" + System.getProperty("user.home"));
System.out.println("第三种获取当前工程的系统缓存临时目录:" + System.getProperty("java.io.tmpdir"));
}
六:创建临时文件,在虚拟机正常关闭后自动删除
File temp = File.createTempFile("superman", ".temp");
temp.deleteOnExit();
int index = -1;
try (
BufferedWriter out = new BufferedWriter(new FileWriter(temp));
) {
out.write("临时文件---------------------");
out.write("dwadawdawdawd");
} catch (IOException e) {
System.err.println("写入失败!");
} finally {
try (
FileInputStream inputStream = new FileInputStream(temp);
) {
byte[] bb = new byte[2048];
index = inputStream.read(bb);
System.out.println(new String(bb, 0, index));
} catch (IOException ee) {
System.out.println("读取失败!");
}
}
System.out.println("临时文件目录(文件可能已被删除):" + temp.getCanonicalPath());