java文件操作(全)
File操作(最全的)
1.文件
1.标准文件:就像图片,音乐文件等。
2.目录文件:也就是平常所说的文件夹。
3.虚拟内存文件:系统在运行程序时生成的临时性文件。
2.文件的路径
1.相对路径:相对于某一文件的路径,形象地说是把两文件的绝对路径相同的部分砍掉,剩下的就是相对路径
如:
A文件是"D:\My Documents\StudySample\src\cn\xmh",
B文件是"D:\My Documents\StudySample\src\netjava\cjl",
则B相对A的路径是"\netjava\cjl";
2.绝度路径:从磁盘根目录算起的路径名
如:"G:\TDDOWNLOAD\数据结构"。
3.File是一个类,位于java.io包中。我们可以用File类创建文件对象,并对文件对象进行各种操作,如读写数据。
4.File类中的构造器以及各种方法
1.构造器
1.最常用的一种,根据字符串型的路径名创建文件对象
File(String pathname)
示例:
String path = "D:\\My Documents\\StudySample";
java.io.File file = new java.io.File(path);
2.在一个父目录对象下面创建一个名字为child的文件对象,child为要创建的文件的名字
File(File parent,String child)//这里的parent是File类型的,也就是说它是文件对象
File(String parent,String child)//这里的parent是String类型的,它代表的是父目录的路径
2.文件对象操作方法
1.exists():判断File对象指向的文件是否存在,返回一个boolean类型的值,true或者false。
2.isDirectory():判断File对象指向的文件是否为目录,返回一个boolean类型的值,true或者false。
3.isFile():判断File对象指向的文件是否是标准文件,返回一个boolean类型的值,true或者false。
4.getName():获取文件的名字(不带文件的路径),返回的是String类型的值。
5.length():得到File对象指向文件的长度,以字节计算,返回一个长整形的值(long);
注意:在系统中,文件夹(目录)的大小为零,也就是不占用空间,使用length()
时返回的是0
6.mkdir():根据File对象的名字(路径)创建一个目录(文件夹),如果是相对目录,则新建的目录在当前目录下
如在工程StudySample中运行
String path = "study";
java.io.File file = new java.io.File(path);
file.createNewFile();
这样就会在StudySample目录下创建一个名为"study"的文件夹(目录)。
如果已经存在同名的文件,则抛出异常信息。
7.mkdirs():如果File对象名字有多级目录,则可以调用该方法一次性创建多级目录。
8.createNewFile():用来创建标准文件的方法
如下示例:
String path = "D:\\My Documents\\StudySample\\test.txt";
java.io.File file = new java.io.File(path);
file.createNewFile();
这样就会在"D:\My Documents\StudySample"目录下创建一个名为"test.txt"的记事本。
9.delete():调用该方法可以删除File对象所指向的文件。
5.文件的操作实例:
import java.io.File;
public class FileExercise {
/**
* @param args
*/
public static void main(String[] args) throws Exception {
System.out.println("当前操作系统的名称分隔符是:" + java.io.File.separator);
System.out.println("当前操作系统的路径分隔符是:" + java.io.File.pathSeparator);
// 字符串类型的文件名
String fileName = "xiong.txt";
// 实例化文件对象
java.io.File file = new java.io.File("src", fileName);
java.io.File file1 = new java.io.File(
"D:\\My Documents\\StudySample\\src\\xiong");
java.io.File file2 = new java.io.File(
"D:\\My Documents\\StudySample\\src");
// 创建一个文件
file.createNewFile();
boolean b;// 申明一个boolean类型的变量
// 测试应用程序是否可以执行该文件
b = file.canExecute();
System.out.println("测试应用程序是否可以执行该文件" + b);
// 测试用用程序是否可以读取该文件
b = file.canRead();
System.out.println("测试用用程序是否可以读取该文件" + b);
// 测试用用程序是否可以修改该文件
b = file.canWrite();
System.out.println("测试用用程序是否可以修改该文件" + b);
// 测试此抽象路径名表示的文件或目录是否存在。
b = file.exists();
System.out.println("测试此抽象路径名表示的文件或目录是否存在" + b);
// 按字母顺序比较两个抽象路径名
int i = https://www.360docs.net/doc/e88901793.html,pareTo(file1);
System.out.println(i);
String path;
// 返回此抽象路径名的绝对路径名字符串
path = file.getAbsolutePath();
System.out.println(path);
// 返回此抽象路径名的规范路径名字符串
path = file.getCanonicalPath();
System.out.println(path);
long free;
// 返回此抽象路径名指定的分区中未分配的字节数
free = file.getFreeSpace();
System.out.println("此抽象路径名指定的分区中未分配的字节数" + free);
// 返回由此抽象路径名表示的文件或目录的名称
String name;
name = file.getName();
System.out.println(name);
name = file1.getName();
System.out.println(name);
// 返回此抽象路径名父目录的路径名字符串;如果此路径名没有指定父目录,则返回null
String parentpath;
parentpath = file.getParent();
System.out.println(parentpath);
parentpath = file1.getParent();
System.out.println(parentpath);
// 返回此抽象路径名指定的分区上可用于此虚拟机的字节数
free = file.getUsableSpace();
System.out.println("此抽象路径名指定的分区上可用于此虚拟机的字节数" + free);
// 计算此抽象路径名的哈希码
i = file.hashCode();
System.out.println(i);
// 测试此抽象路径名是否为绝对路径名
b = file.isAbsolute();
System.out.println("file对象的抽象路径名是否为绝对路径名:" + b);
b = file1.isAbsolute();
System.out.println("file1对象的抽象路径名是否为绝对路径名:" + b);
// 返回此抽象路径名表示的文件最后一次被修改的时间
long time = https://www.360docs.net/doc/e88901793.html,stModified();
System.out.println(time);
// 返回由此抽象路径名表示的文件的长度
long length = file.length();
System.out.println("文件的长度:" + length);
// list()-->返回一个字符串数组,这些字符串指定此抽象路径名表示的目录中的文件和目录
String[] array = file2.list();
for (i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
// listFiles()-->返回一个抽象路径名数组,这些路径名表示此抽象路径名表示的目录中的文件
java.io.File[] array1 = file2.listFiles();
for (i = 0; i < array1.length; i++) {
System.out.println(array1[i]);
}
// listRoots()-->列出可用的文件系统根,静态方法
java.io.File[] roots = File.listRoots();
for (i = 0; i < roots.length; i++) {
System.out.println(roots[i]);
}
// 在虚拟机终止时,请求删除此抽象路径名表示的文件或目录。
// file.deleteOnExit();
//创建此抽象路径名指定的目录
file1.mkdir();
//重新命名此抽象路径名表示的文件
java.io.File file4 = new java.io.File("src\\重命名文件");
System.out.println(file1.renameTo(file4));
//设置文件只读
file.setReadOnly();
//设置文件可写
file.setWritable(true);
}
}
1.创建文件夹
File myFolderPath = new File(%%1);
try {
if (!myFolderPath.exists()) {
myFolderPath.mkdir();
}
}
catch (Exception e) {
System.out.println("新建目录操作出错");
e.printStackTrace();
}
2.创建文件
File myFilePath = new File(%%1);
try {
if (!myFilePath.exists()) {
myFilePath.createNewFile();
}
FileWriter resultFile = new FileWriter(myFilePath); PrintWriter myFile = new PrintWriter(resultFile); myFile.println(%%2);
resultFile.close();
}
catch (Exception e) {
System.out.println("新建文件操作出错");
e.printStackTrace();
}
3.删除文件
File myDelFile = new File(%%1);
try {
myDelFile.delete();
}
catch (Exception e) {
System.out.println("删除文件操作出错");
e.printStackTrace();
}
4.删除文件夹
File delFolderPath = new File(%%1);
try {
delFolderPath.delete(); //删除空文件夹
}
catch (Exception e) {
System.out.println("删除文件夹操作出错");
e.printStackTrace();
}
5.删除一个文件下夹所有的文件夹
File delfile=new File(%%1);
File[] files=delfile.listFiles();
for(int i=0;i if(files[i].isDirectory()){ files[i].delete(); } } 6.清空文件夹 File delfilefolder=new File(%%1); try { if (!delfilefolder.exists()) { delfilefolder.delete(); } delfilefolder.mkdir(); } catch (Exception e) { System.out.println("清空目录操作出错"); e.printStackTrace(); } 7.读取文件 // 逐行读取数据 FileReader fr = new FileReader(%%1); BufferedReader br = new BufferedReader(fr); String %%2 = br.readLine(); while (%%2 != null) { %%3 %%2 = br.readLine(); } br.close(); fr.close(); 8.写入文件 // 将数据写入文件 FileWriter fw = new FileWriter(%%1); fw.write(%%2); fw.close(); 9.写入随机文件 try { RandomAcessFile logFile=new RandomAcessFile(%%1,"rw"); long lg=logFile.length(); logFile.seek(%%2); logFile.writeByte(%%3); }catch(IOException ioe){ System.out.println("无法写入文件:"+ioe.getMessage()); } 10.读取文件属性 // 文件属性的取得 File af = new File(%%1); if (af.exists()) { System.out.println(f.getName() + "的属性如下:文件长度为:" + f.length()); System.out.println(f.isFile() ? "是文件" : "不是文件"); System.out.println(f.isDirectory() ? "是目录" : "不是目录"); System.out.println(f.canRead() ? "可读取" : "不"); System.out.println(f.canWrite() ? "是隐藏文件" : ""); System.out.println("文件夹的最后修改日期为:" + new Date(https://www.360docs.net/doc/e88901793.html,stModified())); } else { System.out.println(f.getName() + "的属性如下:"); System.out.println(f.isFile() ? "是文件" : "不是文件"); System.out.println(f.isDirectory() ? "是目录" : "不是目录"); System.out.println(f.canRead() ? "可读取" : "不"); System.out.println(f.canWrite() ? "是隐藏文件" : ""); System.out.println("文件的最后修改日期为:" + new Date(https://www.360docs.net/doc/e88901793.html,stModified())); } if(f.canRead()){ %%2 } if(f.canWrite()){ %%3 } 11.写入属性 File filereadonly=new File(%%1); try { boolean b=filereadonly.setReadOnly(); } catch (Exception e) { System.out.println("拒绝写访问:"+e.printStackTrace()); } 12.枚举一个文件夹中的所有文件夹 //import java.io.*; //import java.util.*; ArrayList folderList.add(%%1); for (int j = 0; j < folderList.size(); j++) { File file = new File(folderList.get(j)); File[] files = file.listFiles(); ArrayList for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { folderList.add(files[i].getPath()); } else { fileList.add(files[i]); } } for (File f : fileList) { %%2=f.toString(); %%3 } } 13.复制文件夹 //import java.io.*; //import java.util.*; ArrayList folderList.add(%%1); ArrayList folderList2.add(%%2); for(int j=0;j (new File(folderList2[j])).mkdirs(); //如果文件夹不存在则建立新文件夹 File folders=new File(folderList[j]); String[] file=folders.list(); File temp=null; try { for (int i = 0; i < file.length; i++) { if(folderList[j].endsWith(File.separator)){ temp=new File(folderList[j]+"/"+file[i]); } else{ temp=new File(folderList[j]+"/"+File.separator+file[i]); } FileInputStream input = new FileInputStream(temp); if(temp.isFile()){ FileInputStream input = new FileInputStream(temp); FileOutputStream output = new FileOutputStream(folderList2[j] + "/" + (temp.getName()).toString()); byte[] b = new byte[5120]; int len; while ( (len = input.read(b)) != -1) { output.write(b, 0, len); } output.flush(); output.close(); input.close(); } if(temp.isDirectory()){//如果是子文件夹 folderList.add(folderList[j]+"/"+file[i]); folderList2.add(folderList2[j]+"/"+file[i]); } } } catch (Exception e) { System.out.println("复制整个文件夹内容操作出错"); e.printStackTrace(); } } 14.复制一个文件夹下所有的文件夹到另一个文件夹下 File copyfolders=new File(%%1); File[] copyfoldersList=copyfolders.listFiles(); for(int k=0;k if(copyfoldersList[k].isDirectory()){ ArrayList folderList.add(copyfoldersList[k].getPath()); ArrayList folderList2.add(%%2+"/"+copyfoldersList[k].getName()); for(int j=0;j (new File(folderList2[j])).mkdirs(); //如果文件夹不存在则建立新文件夹 File folders=new File(folderList[j]); String[] file=folders.list(); File temp=null; try { for (int i = 0; i < file.length; i++) { if(folderList[j].endsWith(File.separator)){ temp=new File(folderList[j]+"/"+file[i]); } else{ temp=new File(folderList[j]+"/"+File.separator+file[i]); } FileInputStream input = new FileInputStream(temp); if(temp.isFile()){ FileInputStream input = new FileInputStream(temp); FileOutputStream output = new FileOutputStream(folderList2[j] + "/" + (temp.getName()).toString()); byte[] b = new byte[5120]; int len; while ( (len = input.read(b)) != -1) { output.write(b, 0, len); } output.flush(); output.close(); input.close(); } if(temp.isDirectory()){//如果是子文件夹 folderList.add(folderList[j]+"/"+file[i]); folderList2.add(folderList2[j]+"/"+file[i]); } } } catch (Exception e) { System.out.println("复制整个文件夹内容操作出错"); e.printStackTrace(); } } } } 15.移动文件夹 ArrayList folderList.add(%%1); ArrayList folderList2.add(%%2); for(int j=0;j (new File(folderList2[j])).mkdirs(); //如果文件夹不存在则建立新文件夹 File folders=new File(folderList[j]); String[] file=folders.list(); File temp=null; try { for (int i = 0; i < file.length; i++) { if(folderList[j].endsWith(File.separator)){ temp=new File(folderList[j]+"/"+file[i]); } else{ temp=new File(folderList[j]+"/"+File.separator+file[i]); } FileInputStream input = new FileInputStream(temp); if(temp.isFile()){ FileInputStream input = new FileInputStream(temp); FileOutputStream output = new FileOutputStream(folderList2[j] + "/" + (temp.getName()).toString()); byte[] b = new byte[5120]; int len; while ( (len = input.read(b)) != -1) { output.write(b, 0, len); } output.flush(); output.close(); input.close(); } if(temp.isDirectory()){//如果是子文件夹 folderList.add(folderList[j]+"/"+file[i]); folderList2.add(folderList2[j]+"/"+file[i]); } } } catch (Exception e) { System.out.println("复制整个文件夹内容操作出错"); e.printStackTrace(); } } File movefile=new File(%%1); File[] movefiles=movefile.listFiles(); for(int i=0;i if(files[i].isDirectory()){ files[i].delete(); } } movefile.delete(); 16.移动一个文件夹下所有的文件夹到另一个目录下 File movefolders=new File(%%1); File[] movefoldersList=movefolders.listFiles(); for(int k=0;k if(movefoldersList[k].isDirectory()){ ArrayList folderList.add(movefoldersList[k].getPath()); ArrayList folderList2.add(%%2+"/"+movefoldersList[k].getName()); for(int j=0;j (new File(folderList2[j])).mkdirs(); //如果文件夹不存在则建立新文件夹 File folders=new File(folderList[j]); String[] file=folders.list(); File temp=null; try { for (int i = 0; i < file.length; i++) { if(folderList[j].endsWith(File.separator)){ temp=new File(folderList[j]+"/"+file[i]); } else{ temp=new File(folderList[j]+"/"+File.separator+file[i]); } FileInputStream input = new FileInputStream(temp); if(temp.isFile()){ FileInputStream input = new FileInputStream(temp); FileOutputStream output = new FileOutputStream(folderList2[j] + "/" + (temp.getName()).toString()); byte[] b = new byte[5120]; int len; while ( (len = input.read(b)) != -1) { output.write(b, 0, len); } output.flush(); output.close(); input.close(); temp.delete(); } if(temp.isDirectory()){//如果是子文件夹 folderList.add(folderList[j]+"/"+file[i]); folderList2.add(folderList2[j]+"/"+file[i]); } } } catch (Exception e) { System.out.println("复制整个文件夹内容操作出错"); e.printStackTrace(); } } movefoldersList[k].delete(); } } 17.以一个文件夹的框架在另一个目录创建文件夹和空文件 ArrayList folderList.add(%%1); ArrayList folderList2.add(%%2); for(int j=0;j (new File(folderList2[j])).mkdirs(); //如果文件夹不存在则建立新文件夹 File folders=new File(folderList[j]); String[] file=folders.list(); File temp=null; try { for (int i = 0; i < file.length; i++) { if(folderList[j].endsWith(File.separator)){ temp=new File(folderList[j]+"/"+file[i]); } else{ temp=new File(folderList[j]+"/"+File.separator+file[i]); } FileInputStream input = new FileInputStream(temp); if(temp.isFile()){ if (!temp.exists()) { temp.createNewFile(); } } if(temp.isDirectory()){//如果是子文件夹 folderList.add(folderList[j]+"/"+file[i]); folderList2.add(folderList2[j]+"/"+file[i]); } } } catch (Exception e) { System.out.println("复制整个文件夹内容操作出错"); e.printStackTrace(); } } 18.复制文件 int bytesum = 0; int byteread = 0; File oldfile = new File(%%1); try { if (oldfile.exists()) { //文件存在时 InputStream inStream = new FileInputStream(oldfile); //读入原文件FileOutputStream fs = new FileOutputStream(new File(%%2,oldfile.getName())); byte[] buffer = new byte[5120]; int length; while ( (byteread = inStream.read(buffer)) != -1) { bytesum += byteread; //字节数文件大小 System.out.println(bytesum); fs.write(buffer, 0, byteread); } inStream.close(); } } catch (Exception e) { System.out.println("复制单个文件操作出错"); e.printStackTrace(); } 19.复制一个文件夹下所有的文件到另一个目录 File copyfiles=new File(%%1); File[] files=copyfiles.listFiles(); for(int i=0;i if(!files[i].isDirectory()){ int bytesum = 0; int byteread = 0; try { InputStream inStream = new FileInputStream(files[i]); //读入原文件 FileOutputStream fs = new FileOutputStream(new File(%%2,files[i].getName()); byte[] buffer = new byte[5120]; int length; while ( (byteread = inStream.read(buffer)) != -1) { bytesum += byteread; //字节数文件大小 System.out.println(bytesum); fs.write(buffer, 0, byteread); } inStream.close(); } catch (Exception e) { System.out.println("复制单个文件操作出错"); e.printStackTrace(); } } } 20.提取扩展名 String %%2=(new File(%%1)).getName().split(".")[1]; 21.提取文件名 String %%2=(new File(%%1)).getName().split("//")[1]; 22.提取文件路径 String %%2=(new File(%%1)).getPath(); 23.替换扩展名 File replaceExt=new File(%%1); replaceExt.renameTo(replaceExt.getName().split(".")[0]+"."+%%2); 24.追加路径 %%3=%%2+"/"+%%1 25.移动文件 int bytesum = 0; int byteread = 0; File oldfile = new File(%%1); try { if (oldfile.exists()) { //文件存在时 InputStream inStream = new FileInputStream(oldfile); //读入原文件 FileOutputStream fs = new FileOutputStream(new File(%%2,oldfile.getName())); byte[] buffer = new byte[5120]; int length; while ( (byteread = inStream.read(buffer)) != -1) { bytesum += byteread; //字节数文件大小 //System.out.println(bytesum); fs.write(buffer, 0, byteread); } inStream.close(); oldfile.delete(); } } catch (Exception e) { System.out.println("复制单个文件操作出错"); e.printStackTrace(); } 26.移动一个文件夹下所有文件到另一个目录 File movefile=new File(%%1); File[] movefiles=movefile.listFiles(); for(int i=0;i if(movefiles[i].isFile()){ int bytesum = 0; int byteread = 0; File oldfile = new File(movefiles[i]); try { if (oldfile.exists()) { //文件存在时 InputStream inStream = new FileInputStream(oldfile); //读入原文件 FileOutputStream fs = new FileOutputStream(new File(%%2,oldfile.getName())); byte[] buffer = new byte[5120]; int length; while ( (byteread = inStream.read(buffer)) != -1) { bytesum += byteread; //字节数文件大小 //System.out.println(bytesum); fs.write(buffer, 0, byteread); } inStream.close(); oldfile.delete(); } } catch (Exception e) { System.out.println("复制单个文件操作出错"); e.printStackTrace(); } } } 27.指定目录下搜索文件 private void doSearch(String filter, String path) { File file = new File(path); if(file.exists()) { if(file.isDirectory()) { File[] fileArray = file.listFiles(); for(File f:fileArray) { if(f.isDirectory()) { doSearch(filter,f.getPath()); } else { if(f.getName().indexOf(filter ) >= 0) { countFiles++; result.append(f.getPath () + "\r\n"); } } statusShow1.setText(f.getPath()); } statusShow2.setText("The numbers of files had been found:" + countFiles); } else { System.out.println("Couldn't open the path!"); } } else { System.out.println("The path had been apointed was not Exist!"); } } 28.打开对话框 JFileChooser Jfc = new JFileChooser(); //建立选择档案对话方块盒 Jfc %%1 = Jfc.getSelectedFile(); 29.文件分割 //import java.io.* try { File f=new File(%%1); FileInputStream fileInputStream = new FileInputStream(f); byte[] buffer = new byte[fileInputStream.available()]; FileInputStream.read(buffer); fileInputStream.close(); String strFileName = f.getName(); FileOutputStream fileOutputStream = new FileOutputStream(new File(%%2+"\\"+ strFileName + "1")); fileOutputStream.write(buffer,0,buffer.length/2); fileOutputStream.close(); fileOutputStream = new FileOutputStream(new File(%%2+"\\"+ strFileName + "2")); fileOutputStream.write(buffer, buffer.length/2, buffer.length-buffer.length/2); fileOutputStream.close(); } catch (ArrayIndexOutOfBoundsException e) { System.out.print("using FileStreamDemo src des"); e.printStackTrace(); } catch(IOException e){ e.printStackTrace(); } 30.文件合并 //import java.io.* String strFileName = %%1.substring(%%https://www.360docs.net/doc/e88901793.html,stIndexOf("\\") + 1); try { FileInputStream fileInputStream1 = new FileInputStream(new File(%%2 + strFileName + "1")); FileInputStream fileInputStream2 = new FileInputStream(new File(%%2 + strFileName + "2")); byte[] buffer = new byte[fileInputStream1.available()+fileInputStream2.available()]; FileInputStream.read(buffer, 0, fileInputStream1.available()); FileInputStream2.read(buffer, fileInputStream1.available(), fileInputStream2.available()); fileInputStream.close(); fileInputStream2.close(); FileOutputStream fileOutputStream = new FileOutputStream(new File(%%2+"\\"+ strFileName)); fileOutputStream.write(buffer,0,buffer.length); fileOutputStream.close(); catch(IOException e){ e.printStackTrace(); } 31.文件简单加密 //读文件 FileStream fsr = new FileStream(%%1, FileMode.Open, FileAccess.Read); byte[] btArr = new byte[fsr.Length]; fsr.Read(btArr, 0, btArr.Length); fsr.Close(); for (int i = 0; i < btArr.Length; i++) //加密 { int ibt = btArr[i]; ibt += 100; ibt %= 256; btArr[i] = Convert.ToByte(ibt); } //写文件 string strFileName = Path.GetExtension(%%1); FileStream fsw = new FileStream(%%2+"/" + "enc_" + strFileName, FileMode.Create, FileAccess.Write); fsw.Write(btArr, 0, btArr.Length); fsw.Close(); 32.文件简单解密 FileStream fsr = new FileStream(%%1, FileMode.Open, FileAccess.Read); byte[] btArr = new byte[fsr.Length]; fsr.Read(btArr, 0, btArr.Length); fsr.Close(); for (int i = 0; i < btArr.Length; i++) //解密 { int ibt = btArr[i]; ibt -= 100; ibt += 256; ibt %= 256; btArr[i] = Convert.ToByte(ibt); } //写文件 string strFileName = Path.GetExtension(%%1); FileStream fsw = new FileStream(%%2 +"/" + strFileName, FileMode.Create, FileAccess.Write); fsw.Write(btArr, 0, btArr.Length); fsw.Close(); 33.文件简单解密 //import java.io.* try { File f=new File(%%1); String strFileName = f.getName(); FileInputStream fileInputStream = new FileInputStream(%%2+"\\enc_"+strFilename); byte[] buffer = new byte[fileInputStream.available()]; FileInputStream.read(buffer); fileInputStream.close(); for(int i=0;i { int ibt=buffer[i]; ibt-=100; ibt+=256; ibt%=256; buffer[i]=(byte)ibt; }