目录
一:File类的使用
1、File类的概述
1、java.io.File类:文件和文件目录路径的抽象表达形式,与平台无关
2、File类能够新建、删除、重命名文件和目录,但不能访问文件内容本身,如果需要访问,需要使用输入、输出流
3、想要在java中表示一个真正存在的文件和目录,则必须有一个File对象
2、File的构造器
public File(pathname)
以pathname为路径创建File对象,可以时绝对路径或相对路径
相对路径:是相对于某个位置开始的
绝对路径:是一个固定的路径,从盘符开始
public File(String parent,String child)
以parent为父路径,child为子路径创建File对象
public File(File parent,String child)
根据一个父File对象和一个子路径创建File对象
注意点:路径中的每级路径之间用一个路径分隔符分开
路径分割符和系统有关:
windows和DOS系统:“\”;
UNIX和URL:“/”;
File file1 = new File("d:\\program\\info.txt");
File file2 = new File("d:" + File.separator + "program" + File.separator + "info.txt");
File file3 = new File("d:/program");
二、通过字节流实现文本的赋值
①:通过程序获取文本内容
public String readFileBytes(String path) {
//读取指定路径的文章内容
byte[] b = null;
FileInputStream fis = null;
try {
fis = new FileInputStream(path);
b = new byte[fis.available()];//byte数组的长度设置为可从输入流读取的字节的总长度
int len;
while ((len = fis.read(b)) != -1) {//读取
fis.read(b);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null)
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return new String(b);
}
②将读取到的字符串,复制到新的文件中
public void writeFileBytes(String path, String s) {
byte[] b = null;
FileOutputStream fos = null;
try {
fos = new FileOutputStream(path);
b = s.getBytes();//将字符串转换为byte型字节数组
fos.write(b);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fos != null)
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}