三种文件创建方操作:
import org.testng.annotations.Test; import java.io.File; import java.io.IOException; public class FileTest { public static void main(){ } //方式1 @Test public void create1() throws IOException { String filePath = "d:\\file1.txt"; File file = new File(filePath); try { file.createNewFile(); System.out.println("创建文件1成功"); }catch (IOException e){ e.printStackTrace(); } } //方式2 @Test public void create2(){ File parentFile = new File("D:\\"); String fileName = "file2.txt"; File file = new File(parentFile,fileName); try { file.createNewFile(); System.out.println("文件2 创建成功"); } catch (IOException e) { throw new RuntimeException(e); } } //方式3 @Test public void create3(){ String parentPath = "d:\\"; String filePath = "file3.txt"; File file = new File(parentPath,filePath); try { file.createNewFile(); System.out.println("文件3创建成功"); } catch (IOException e) { throw new RuntimeException(e); } } }
获取文件的相关信息:
常见方法:
import org.testng.annotations.Test; import javax.xml.transform.Source; import javax.xml.transform.sax.SAXSource; import java.io.File; import java.sql.SQLOutput; public class FileFormation { public static void main(String[] args){ } // 获取文件信息 @Test public void Info(){ //先创建文件对象 File file = new File("D:\\file1.txt"); //调用相应方法,得到相应信息 System.out.println("文件名称:"+file.getName()); System.out.println("文件绝对路径:"+file.getAbsoluteFile()); System.out.println("文件父目录:"+file.getParent()); System.out.println("文件大小(字节):"+file.length()); System.out.println("文件是否存在:"+file.exists()); System.out.println("是否是文件:"+file.isFile()); System.out.println("是否是目录:"+file.isDirectory()); } }
目录的操作:
import org.testng.annotations.Test; import java.io.File; public class FileDirectory { public static void main(String[] args){ } @Test //删除文件 public void FileDelete(){ String filePath = "D:\\file1.txt"; File file = new File(filePath); if(file.exists()) { if (file.delete()) { System.out.println(filePath + " 删除成功"); } else { System.out.println(filePath + " 删除失败"); }; }else{ System.out.println(filePath+ " 文件不存在"); } } //删除目录 @Test public void FileDeleteD(){ String filePath = "D:\\file1.txt"; File file = new File(filePath); if(file.exists()) { if (file.delete()) { System.out.println(filePath + "删除成功"); } else { System.out.println(filePath + "删除失败"); }; }else{ System.out.println(filePath+ "目录不存在"); } } //判断目录是否存在,不存在就创建 @Test public void fileDeleteD1(){ String dirPath = "D:\\test\\dir1.txt"; File file = new File(dirPath); if(file.exists()){ System.out.println(dirPath + "该目录已经存在"); }else{ if(file.mkdir()){ System.out.println("创建成功"); }else{ System.out.println("创建失败"); }; } } }
标签:文件,常用,java,File,filePath,System,file,println,out From: https://www.cnblogs.com/zhangsanlisi411/p/16865396.html