文件和目录
- 文件创建
- 目录创建
- 文件删除
- 目录删除
1.文件创建
直接根据文件完整url创建
filename = "Desktop/input.txt";
File f = new File(filename);
if(!f.exists())
f.createNewFile();
目录创建
目录创建有两种:mkdir() 和 mkdirs() ; 说说他们的区别:
mkdir()创建抽象路径名指定的目录;
mkdirs()创建抽象路径名指定的目录,包括所有必须但不存在的父目录;
文件创建和文件夹创建的操作是密不可分,有一些需要注意:
划重点:
1、File类的createNewFile根据抽象路径创建一个新的空文件,当抽象路径制定的文件存在时,创建失败。
2、File类的mkdir方法根据抽象路径创建目录。
3、File类的mkdirs方法根据抽象路径创建目录,包括创建必需但不存在的父目录。
4、File类的createTempFile方法创建临时文件,可以制定临时文件的文件名前缀、后缀及文件所在的目录,如果不指定目录,则存放在系统的临时文件夹下。
5、除mkdirs方法外,以上方法在创建文件和目录时,必须保证目标文件不存在,而且父目录存在,否则会创建失败。
我们看一个完整的例子:
public static boolean createFile(String destFileName) {
File file = new File(destFileName);
if (file.exists()) {
System.out.println("创建单个文件" + destFileName + "失败,目标文件已存在!");
return false;
}
if (destFileName.endsWith(File.separator)) {
System.out.println("创建单个文件" + destFileName + "失败,目标文件不能为目录!");
return false;
}
//判断目标文件所在的目录是否存在
if (!file.getParentFile().exists()) {
//如果目标文件所在的目录不存在,则创建父目录
System.out.println("目标文件所在目录不存在,准备创建它!");
if (!file.getParentFile().mkdirs()) {
System.out.println("创建目标文件所在目录失败!");
return false;
}
}
//创建目标文件
try {
if (file.createNewFile()) {
System.out.println("创建单个文件" + destFileName + "成功!");
return true;
} else {
System.out.println("创建单个文件" + destFileName + "失败!");
return false;
}
} catch (IOException e) {
e.printStackTrace();
System.out.println("创建单个文件" + destFileName + "失败!" + e.getMessage());
return false;
}
}
删除文件
删除文件比较简单
public static void deleteFile(String destFileName) {
File file = new File(destFileName);
if (!file.exists())
return ;
file.delete();
}
删除文件夹
删除文件夹时,要递归遍历所有的文件和文件夹,然后逐个删除;
// 删除某个文件夹下的所有文件夹和文件
public static boolean deletefile(String delpath) throws Exception {
File file = new File(delpath);
if (file.isDirectory()) {
String[] filelist = file.list();
for (String delFile : filelist) {
File delfile = new File(delpath + File.separator + delFile);
if (delfile.isDirectory()) {
deletefile(delpath + File.separator + delFile);
} else
System.out.println("正在删除文件:" + delfile.getPath() + ",删除是否成功:" + delfile.delete());
}
System.out.println("正在删除空文件夹:" + file.getPath() + ",删除是否成功:" + file.delete());
} else
System.out.println("正在删除文件:" + file.getPath() + ",删除是否成功:" + file.delete());
return true;
}
读写文件
读文件
按字节、字符、行读取:
/**
* 以字节为单位读取文件,常用于读二进制文件,如图片、声音、影像等文件。
*/
public static void readFileByBytes(String fileName) {
File file = new File(fileName);
InputStream in = null;
try {
System.out.println("以字节为单位读取文件内容,一次读一个字节:");
// 一次读一个字节
in = new FileInputStream(file);
int tempbyte;
while ((tempbyte = in.read()) != -1) {
System.out.write(tempbyte);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
return;
}
try {
System.out.println("以字节为单位读取文件内容,一次读多个字节:");
// 一次读多个字节
byte[] tempbytes = new byte[100];
int byteread = 0;
in = new FileInputStream(fileName);
ReadFromFile.showAvailableBytes(in);
// 读入多个字节到字节数组中,byteread为一次读入的字节数
while ((byteread = in.read(tempbytes)) != -1) {
System.out.write(tempbytes, 0, byteread);
}
} catch (Exception e1) {
e1.printStackTrace();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e1) {
}
}
}
}
/**
* 以字符为单位读取文件,常用于读文本,数字等类型的文件
*/
public static void readFileByChars(String fileName) {
File file = new File(fileName);
Reader reader = null;
try {
System.out.println("以字符为单位读取文件内容,一次读一个字节:");
// 一次读一个字符
reader = new InputStreamReader(new FileInputStream(file));
int tempchar;
while ((tempchar = reader.read()) != -1) {
// 对于windows下,\r\n这两个字符在一起时,表示一个换行。
// 但如果这两个字符分开显示时,会换两次行。
// 因此,屏蔽掉\r,或者屏蔽\n。否则,将会多出很多空行。
if (((char) tempchar) != '\r') {
System.out.print((char) tempchar);
}
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
System.out.println("以字符为单位读取文件内容,一次读多个字节:");
// 一次读多个字符
char[] tempchars = new char[30];
int charread = 0;
reader = new InputStreamReader(new FileInputStream(fileName));
// 读入多个字符到字符数组中,charread为一次读取字符数
while ((charread = reader.read(tempchars)) != -1) {
// 同样屏蔽掉\r不显示
if ((charread == tempchars.length)
&& (tempchars[tempchars.length - 1] != '\r')) {
System.out.print(tempchars);
} else {
for (int i = 0; i < charread; i++) {
if (tempchars[i] == '\r') {
continue;
} else {
System.out.print(tempchars[i]);
}
}
}
}
} catch (Exception e1) {
e1.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
}
/**
* 以行为单位读取文件,常用于读面向行的格式化文件
*/
public static void readFileByLines(String fileName) {
File file = new File(fileName);
BufferedReader reader = null;
try {
System.out.println("以行为单位读取文件内容,一次读一整行:");
reader = new BufferedReader(new FileReader(file));
String tempString = null;
int line = 1;
// 一次读入一行,直到读入null为文件结束
while ((tempString = reader.readLine()) != null) {
// 显示行号
System.out.println("line " + line + ": " + tempString);
line++;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
}
参考
https://www.cnblogs.com/lovebread/archive/2009/11/23/1609122.html
这里多说一点关于“回车、换行”的题外话:-Unix系统里,每行结尾只有”<换行>”,即 “\n”;
-Windows系统里面,每行结尾是”<回车><换行>”,即 “\r\n”;
-Mac系统里,每行结尾是”<回车>”。即 “\r”;一个直接后果是,Unix/Mac系统下的文件在Windows里打开的话,所有文字会变成一行;而Windows里的文件在Unix/Mac下打开的话,在每行的结尾可能会多出一个^M符号。
写文件
将内容追加到文件尾部
有两种方式:
- 追加方式:new FileOutputStream(filename, true) 使用输出流时指定true;
- 随机方式:使用 RandomAccessFile;
注意:
如果不指定追加方式,默认写是会将原内容擦除,重新从头开始的!
/*
* 追加方式:new FileOutputStream(filename, true)
* */
public static void writeMethod2(String filename, String content) {
BufferedWriter out = null;
try {
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filename, true)));
out.write(content + "\r\n");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/*
* 使用RandomAccessFile,指向文件尾部开始写
* */
public static void writeMethod3(String filename, String content) {
try {
// 打开一个随机访问文件流,按读写方式
RandomAccessFile randomFile = new RandomAccessFile(filename, "rw");
// 文件长度,字节数
long fileLength = randomFile.length();
// 将写文件指针移到文件尾。
randomFile.seek(fileLength);
randomFile.writeBytes(content + "\r\n");
randomFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
RandomAccessFile
RandomAccessFile是用来访问那些保存数据记录的文件的,你就可以用seek( )方法来访问记录,并进行任意位置读写了。这些记录的大小不必相同;但是其大小和位置必须是可知的。但是该类仅限于操作文件。
=================***注意***===================
这类不算是IO体系中的子类。
而是直接继承Object
但是它是IO包中的成员,因为它具备读和写的功能。
能完成读写的原理是内部封装了字节输入流和输出流。
而且内部还封装了一个数组,通过指针对数组的元素进行操作。
可通过getFilePointer获取指针位置。
也可通过seek改变指针的位置。
通过构造函数可以看出,该类只能操作文件。
操作文件有4种模式:"r"、"rw"、"rws" 或 "rwd"
如果模式为只读r。则不会创建文件,而是会去读取一个已经存在的文件,如果读取的文件不存在则会出现异常。
如果模式为rw读写。如果文件不存在则会去创建文件,如果存在则不会创建。
RandomAccessFile操作演示:
package com.lwj.demo;
import java.io.*;
public class RandomAccessFileDemo {
public static void main(String[] args) throws Exception {
RandomAccessFile file = new RandomAccessFile("file", "rw");
// 以下向file文件中写数据
file.writeInt(20);// 占4个字节
file.writeDouble(8.236598);// 占8个字节
file.writeUTF("这是一个UTF字符串");// 这个长度写在当前文件指针的前两个字节处,可用readShort()读取
file.writeBoolean(true);// 占1个字节
file.writeShort(395);// 占2个字节
file.writeLong(2325451l);// 占8个字节
file.writeUTF("又是一个UTF字符串");
file.writeFloat(35.5f);// 占4个字节
file.writeChar('a');// 占2个字节
file.seek(0);// 把文件指针位置设置到文件起始处
// 以下从file文件中读数据,要注意文件指针的位置
System.out.println("——————从file文件指定位置读数据——————");
System.out.println(file.readInt());
System.out.println(file.readDouble());
System.out.println(file.readUTF());
file.skipBytes(3);// 将文件指针跳过3个字节,本例中即跳过了一个boolean值和short值。
System.out.println(file.readLong());
file.skipBytes(file.readShort()); // 跳过文件中“又是一个UTF字符串”所占字节,注意readShort()方法会移动文件指针,所以不用加2。
System.out.println(file.readFloat());
//以下演示文件复制操作
System.out.println("——————文件复制(从file到fileCopy)——————");
file.seek(0);
RandomAccessFile fileCopy=new RandomAccessFile("fileCopy","rw");
int len=(int)file.length();//取得文件长度(字节数)
byte[] b=new byte[len];
file.readFully(b);
fileCopy.write(b);
System.out.println("复制完成!");
}
}
使用RandomAccessFile不需要判断文件存在不存在(rw模式下),如果文件不存在则会创建文件,存在则不会!
RandomAccessFile 插入写示例:
/**
*
* @param skip 跳过多少过字节进行插入数据
* @param str 要插入的字符串
* @param fileName 文件路径
*/
public static void beiju(long skip, String str, String fileName){
try {
RandomAccessFile raf = new RandomAccessFile(fileName,"rw");
if(skip < 0 || skip > raf.length()){
System.out.println("跳过字节数无效");
return;
}
byte[] b = str.getBytes();
raf.setLength(raf.length() + b.length);
for(long i = raf.length() - 1; i > b.length + skip - 1; i--){
raf.seek(i - b.length);
byte temp = raf.readByte();
raf.seek(i);
raf.writeByte(temp);
}
raf.seek(skip);
raf.write(b);
raf.close();
} catch (Exception e) {
e.printStackTrace();
}
}
插入过程如图:
所以利用RandomAccessFile实现文件的多线程下载也非常Easy;
可以参考下面这篇博客:
http://blog.csdn.net/akon_vm/article/details/7429245
参考:
http://blog.csdn.net/world_java/article/details/7560121
http://blog.csdn.net/akon_vm/article/details/7429245