java的一些语法基础(三)

如何创建一个文件夹?

/**
* 根据路径创建文件夹
* @param folderPath
* @return boolean
*/
public static boolean createFolder(String folderPath) {
boolean flag = false;
File f = new File(folderPath);
flag = f.mkdirs();
return flag;
}
/**
* @param args
*/
public static void main(String[] args) {
System.out.println(createFolder("e:\\fxf\\fxf"));;
}

如何列出目录下的文件?

/**
* 根据路径创建文件夹
* @param folderPath
* @return boolean
*/
public static boolean createFolder(String folderPath) {
boolean flag = false;
File f = new File(folderPath);
flag = f.mkdirs();
return flag;
}
/**
* @param args
*/
public static void main(String[] args) {
System.out.println(createFolder("e:\\fxf\\fxf"));;
}

如何遍历一个目录及其子目录下的所有文件?

/**
* 根据路径,如果是文件夹,输出该文件夹下文件名以及子文件夹的文件名称
* @param folderPath
*/
public static void displayUnderFolderAndChildFloder(String folderPath) {
File f = new File(folderPath);
if (f.isDirectory()) {
System.out.println(f.getAbsolutePath() + "文件夹下文件有:");
File[] fileArray = f.listFiles();
if (fileArray != null) {
for (int m = 0; m < fileArray.length; m++) {
if (fileArray[m].isDirectory()) {
displayUnderFolderAndChildFloder(fileArray[m].getAbsolutePath());
} else {
System.out.println(fileArray[m].getName());
}
}
}
} 
}
/**
* @param args
*/
public static void main(String[] args) {
displayUnderFolderAndChildFloder("E:\\data");
}
 

如何创建一个文件?

/**
* 根据路径创建文件
* @param folderPath
* @return boolean 
*/
public static boolean createFile(String folderPath) {
boolean flag = false;
File f = new File(folderPath);
try {
flag = f.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
return flag;
}

如何获取文件的长度?

/**
* 根据文件路径获取文件长度,如果是文件夹返回0
* @param filePath
* @return String
*/<strong>
</strong>public static String getFileLength(String filePath) {
String fileLength = "";
File f = new File(filePath);
if (!f.isDirectory()) {

try {
FileInputStream fInput = new FileInputStream(f);
fileLength = String.valueOf(fInput.available());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
//fileLength = String.valueOf(f.length());//该方法好像也可以,测试文字型文件,两种获取长度都一样
} else {
fileLength = "0";
}
return fileLength;
}

如何判断指定的文件是否存在?

待续。。。

如何按照指定的编码向文件中写入文本?
如何在文件末尾追加文本?
如何按行读取文本文件的内容?
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值