Java自学笔记——文件
创建
package com.hz.file;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
public class FileCreate {
public static void main(String[] args) {
}
@Test
public void creat01(){
String filePath = "c:\\D\\news1.txt";
File file = new File(filePath);
try {
file.createNewFile();
System.out.println("创建成功");
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void creat02(){
File parentfile = new File("c:\\D\\");
String fileName = "news2.txt";
File file = new File(parentfile, fileName);
try {
file.createNewFile();
System.out.println("创建成功");
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void creat03(){
String parentPath = "c:\\D\\";
String fileName = "news3.txt";
File file = new File(parentPath, fileName);
try {
file.createNewFile();
System.out.println("创建成功");
} catch (IOException e) {
e.printStackTrace();
}
}
}
获取相关信息
package com.hz.file;
import org.junit.Test;
import java.io.File;
public class FileInformation {
public static void main(String[] args) {
}
@Test
public void info(){
File file = new File("c:\\D\\news1.txt");
System.out.println("名字"+file.getName());
System.out.println("绝对路径"+file.getAbsolutePath());
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());
}
}
目录操作
package com.hz.file;
import org.junit.Test;
import java.io.File;
/
public class Directory_ {
public static void main(String[] args) {
}
@Test
public void m1(){
String filePath = "c:\\D\\news1.txt";
File file = new File(filePath);
if(file.exists()){
if(file.delete()){
System.out.println("删除成功");
}
}else {
System.out.println("文件不存在");
}
}
@Test
public void m2(){
String filePath = "c:\\D\\A";
File file = new File(filePath);
if(file.exists()){
if(file.delete()){
System.out.println("删除成功");
}
}else {
System.out.println("目录不存在");
}
}
@Test
public void m3(){
String filePath = "c:\\D\\A";
File file = new File(filePath);
if(file.exists()){
System.out.println("该目录存在");
}else {
if(file.mkdirs()){
System.out.println("创建成功");
}
}
}
}