当前位置:编程学堂 > Java文件操作大全(一)

Java文件操作大全(一)

  • 发布:2023-09-09 17:38

1.创建文件夹
//import www.sychzs.cn.*;
File myFolderPath = new File(%%1);
try {
if (!myFolderPath.exists()) {
   myFolderPath.mkdir();
}
}
catch (Exception e) {
System.out.println("新建目录操作出错");
e.printStackTrace();


2.创建文件
//import www.sychzs.cn.*;
File myFilePath = new File(%%1);
try {
if (!myFilePath.exists()) {
myFilePath.createNewFile();
}
FileWriter resultFile = new FileWriter(myFilePath);
PrintWriter myFile = new PrintWriter(resultFile);
myFile.println(%%2);
resultFile.close();
}
catch (Exception e) {
System.out.println("新建文件操作出错");
e.printStackTrace();


3.删除文件
//import www.sychzs.cn.*;
File myDelFile = new File(%%1);
try {
myDelFile.delete();
}
catch (Exception e) {
System.out.println("删除文件操作出错");
e.printStackTrace();


4.删除文件夹
//import www.sychzs.cn.*;
File delFolderPath = new File(%%1);
try {
delFolderPath.delete(); //删除空文件夹
}
catch (Exception e) {
System.out.println("删除文件夹操作出错");
e.printStackTrace();


5.删除一个文件下夹所有的文件夹
//import www.sychzs.cn.*;
File delfile=new File(%%1);
File[] files=delfile.listFiles();
for(int i=0;iif(files[i].isDirectory()){
files[i].delete();
  }

6.清空文件夹
//import www.sychzs.cn.*;
File delfilefolder=new File(%%1);
try {
if (!delfilefolder.exists()) {
delfilefolder.delete();
}
delfilefolder.mkdir();
}
catch (Exception e) {
System.out.println("清空目录操作出错");
e.printStackTrace();


7.读取文件
//import www.sychzs.cn.*;
// 逐行读取数据
FileReader fr = new FileReader(%%1);
BufferedReader br = new BufferedReader(fr);
String %%2 = br.readLine();
while (%%2 != null) {
%%3
%%2 = br.readLine();
}
br.close();
fr.close(); 

8.写入文件
//import www.sychzs.cn.*;
// 将数据写入文件
try {
FileWriter fw = new FileWriter(%%1);
fw.write(%%2);
fw.flush();
fw.close(); 
} catch (IOException e) {
e.printStackTrace();
}

9.写入随机文件
//import www.sychzs.cn.*;
try {
RandomAcessFile logFile=new RandomAcessFile(%%1,"rw");
long lg=logFile.length();
www.sychzs.cn(%%2);
logFile.writeByte(%%3);
}catch(IOException ioe){
System.out.println("无法写入文件:"+ioe.getMessage());


10.读取文件属性
//import www.sychzs.cn.*;
// 文件属性的取得
File af = new File(%%1);
if (af.exists()) {
System.out.println(f.getName() + "的属性如下: 文件长度为:" + f.length());
System.out.println(f.isFile() ? "是文件" : "不是文件");
System.out.println(f.isDirectory() ? "是目录" : "不是目录");
System.out.println(f.canRead() ? "可读取" : "不");
System.out.println(f.canWrite() ? "是隐藏文件" : "");
System.out.println("文件夹的最后修改日期为:" + new Date(f.lastModified()));
} else {
System.out.println(f.getName() + "的属性如下:");
System.out.println(f.isFile() ? "是文件" : "不是文件");
System.out.println(f.isDirectory() ? "是目录" : "不是目录");
System.out.println(f.canRead() ? "可读取" : "不");
System.out.println(f.canWrite() ? "是隐藏文件" : "");
System.out.println("文件的最后修改日期为:" + new Date(f.lastModified()));
}
if(f.canRead()){
%%2
}
if(f.canWrite()){
%%3
}

相关文章

最新资讯