import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class IO {
public static void main(String[] args) {
}
// 方式一
@Test
public void createFile() {
String filePath = "d:\\file.txt";
File file = new File(filePath);
try {
file.createNewFile();
System.out.println(file.getName());
} catch (IOException e) {
e.printStackTrace();
}
}
// 方式二
@Test
public void createFile1() {
File parentFile = new File("D:\\");
String fileName = "file2.txt";
File file1 = new File(file, s);
try {
file1.createNewFile();
System.out.println("done!");
} catch (IOException e) {
e.printStackTrace();
}
}
// 方式三
@Test
public void createFile2() {
String parentPath = "d:\\";
String fileName = "file3.txt";
File file = new File(parentPath, filePath);
try {
file.createNewFile();
System.out.println("文件3创建成功");
} catch (IOException e) {
e.printStackTrace();
}
}
// 文件信息
@Test
public void info() {
/**
* 创建文件
*/
File file = new File("D:\\data\\file.txt");
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
/**
* 调用方法得到文件信息
*/
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());
}
// 文件夹(目录)操作
@Test
public void createDir1() {
String dirName = "d:\\data\\test";
File directory = new File(dirName);
try {
boolean hasSucceeded = directory.mkdir();
System.out.println("创建文件夹结果(不含父文件夹):" + hasSucceeded);
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void createDir2() {
String dirName = "d:\\data1\\test";
File directory = new File(dirName);
try {
boolean hasSucceeded = directory.mkdirs();
System.out.println("创建文件夹结果(包含父文件夹):" + hasSucceeded);
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void deleteFile() {
File file = new File("D:\\data\\text.txt");
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
if (file.delete()) {
System.out.println("empty");
} else {
System.out.println(file.getName());
}
}
// 基本键盘输入
public class scanPrintTest {
public static void main(String[] args) {
//创建Scanner对象,接受从控制台输入
Scanner input = new Scanner(System.in);
//接受String类型
String str = input.next();
//输出结果
System.out.println(str);
System.out.println("hello world");
}
}
// 常见键盘输入类型
public class scanTest {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
//double类型的数据
System.out.print("请输入一个double类型的数:");
double d = input.nextDouble();
System.out.println(d);
//int类型的数据
System.out.print("请输入一个int类型的数:");
int i = input.nextInt();
System.out.println();
//字符串类型的数据
System.out.print("请输入-个string类型的数:");
String s = input.next();
System.out.println(s);
}
}
}
标签:文件,File,建立,System,查询,file,println,public,out From: https://www.cnblogs.com/mikasaakerman/p/16861764.html