File.exists() //文件是否存在 返回true or false
File.createNewFile(); //创建文件File.delete //删除文件
File.getParentFile() //获取父目录
File.getParenFile().mkdir() //创建单个父目录,多级用mkdirs()
/** 读取图片以及目录信息
*/
public class Test {
//保留两位小数点
public static double round(double num, int scale) {
double mt = (Math.round(num * Math.pow(10, scale))) / (Math.pow(10, scale));
return mt;
}
public static void main(String args[]) throws IOException {
File file = new File("C:\\Users\\Administrator\\Pictures\\守望屁股.jpg");
if(file.exists() && file.isFile()) { //文件存在并且状态正常
double d = (double)(file.length()) / 1024 / 1024; //字节转兆
System.out.println(round(d,2));
Date date = new Date(file.lastModified()); //获取文件最后一次修改日期
SimpleDateFormat simpledate = new SimpleDateFormat("yyyy-mm-dd");
System.out.println(simpledate.format(date));
}
//列出目录信息
File file2 = new File("C:\\Users"); //读取目录
if(file2.exists() && file2.isDirectory()) { //检查对象是否是文件夹
File[] result = file2.listFiles(); //列出全部子文件夹
for(File r : result) {
System.out.println(r);
}
String[] files = file2.list(); //列出该目录和文件所有名称
for(String f : files) {
System.out.println(f);
}
}
}
}
/*
* 输出全部目录
*/
public class Test {
public static void listDir(File file) {
if(file.isDirectory()) { //当前对象是否为目录
File[] result = file.listFiles(); //当前目录转换数组
if(result != null) {
for(int x = 0;x < result.length;x ++) {
listDir(result[x]); //递归当前子目录
}
}
}
System.out.println(file); //输出目录下的非目录文件
}
public static void main(String args[]) throws IOException {
File file = new File("C:\\Users\\Administrator");
listDir(file);
}
}
/*
* 读取文件数据
*/
public class Test {
public static void main(String args[]) throws IOException {
File file = new File("E:" + File.separator + "Hello.txt");
if(file.exists()) {
InputStream input = new FileInputStream(file);
byte[] bt = new byte[1024]; //创建数组
int len = input.read(bt); //把数据读取到数组里,返回字节数
System.out.println(new String(bt,0,len)); //默认字符集解码实际数组元素构造新String
input.close();
}
}
}
/*
* 写入字符
*/
public class Test {
public static void main(String args[]) throws IOException {
File file = new File("E:" + File.separator + "Hello.txt");
if(!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
String msg = "稳定";
Writer out = new FileWriter(file,true); //创建输入流
out.write(msg);
out.close();
}
}
import java.io.*;
/*
* 字符输入流
*/
public class Test {
public static void main(String args[]) throws IOException {
File file = new File("E:" + File.separator + "Hello.txt");
if(file.exists()) {
Reader in = new FileReader(file);
char[] data = new char[1024];
int len = in.read(data); //字符写入数组以及获取字节个数
System.out.println(new String(data)); //输出数组
in.close();
}
}
}
本文提供了一系列Java文件操作的示例代码,包括文件属性读取、目录遍历、文件读写等基本功能。通过具体实例展示了如何使用Java进行文件长度转换、获取最后修改日期、列出目录信息、读取文件数据及写入字符等操作。
1028

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



