首先实例化File类并填写相应的路径,通过.exists()判断文件是否存在再进行文件创建.createNewFile();,创建完毕后可以使用相应的方法进行查看(变量名.getxxxx)
File file =new File("D:\\wuzhijie.txt"); //引用File类,构建文件镜像对象
file.exists(); //判断文件或则目录是否存在,布尔类型
file.createNewFile(); //创建文件
file.getName() //查看文件名称
file.getAbsolutePath() //查看绝对路径(全路径的意思)
file.getPath() //查看相对路径
file.length() //查看文件大小(字节)
参考代码:
public class Text4 {
public static void main(String[] args) {
File file =new File("D:\\wuzhijie.txt"); //引用File类,构建文件镜像对象
if(!file.exists()){ //判断文件或则目录是否存在,布尔类型
System.out.println("创建成功!!!");
try {
file.createNewFile(); //创建文件代码
} catch (IOException e) {
e.printStackTrace();
}
}else{
System.out.println("已经存在文件");
System.out.println("文件名是:"+file.getName()+"绝对路径是:"+file.getAbsolutePath()+"相对路径是:"+file.getPath()+"文件大小:"+file.length()+"字节");
file.delete();
}
}
}
二.InputStream(读取)
首先实例化FileInputStream类,通过.read();方法读取元素,根据字符情况可能需要转换
.read(); //读取数据
.close(); //关闭流
参考代码:
public class Text5 {
public static void main(String[] args) {
try {
FileInputStream fis =new FileInputStream("E:\\wuzhijie.txt"); //引用指定文件目录
int leng=0; //声明整形int变量用于存储数据
while ((leng=fis.read())!=-1) { //依次读取数据直到为空(-1)并放倒leng变量中
System.out.println((char)leng); //leng出来的是ascii码,需要使用Char变相应字符
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
三.OutputStream(写入)
先实例化FileOutputStream对象并引用目录,通过变量名.write()方法写入相应信息
.write(); //写入信息
.close(); //关闭流
参考代码:
public class Text6 {
public static void main(String[] args) {
OutputStream os = null; //实例化类
try {
os =new FileOutputStream("D:\\wuzhijie.txt"); //引用指定文件目录
String str = "好好学习,天天向上"; //需要插入的字符
byte [] b = str.getBytes(); //因中文一字等于两字符,需使用byte储存
os.write(b, 0, b.length); //使用write方法(变量,位置,位置)
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
os.close(); //关闭流
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
本文介绍了如何使用Java进行基本的文件操作,包括文件的创建、读取和写入。通过实例展示了如何利用File类来判断文件是否存在,如何创建新文件,并获取文件的相关属性如名称、路径及大小等;同时演示了如何使用InputStream读取文件内容和OutputStream向文件写入数据。
&spm=1001.2101.3001.5002&articleId=80098164&d=1&t=3&u=bb3661c25d934783bb12d54d01fdc067)
1520

被折叠的 条评论
为什么被折叠?



