JAVA学习(八):JAVA文件编程

本博文主要介绍JAVA文件编程,主要包括通过JDK提供的I/O来从文件读取和写入数据、字节流读写文件的方法、字符流读写文件的方法、如何使用File类创建、删除和遍历文件与目录等操作。


不管是C/C++还是JAVA,都可能生成一些持久性数据,我们可以将数据存储在文件或数据库中,但是对于一些简单性的数据,如果存储在数据库中,则会显得有点得不偿失了,那么,如何在JAVA中将数据存储在文件中就成了中小型程序必须掌握的基本技能了。


下面一一讲解File类简介与文件的创建、删除、重命名,文件夹的创建、重命名、删除,文件属性的读取,文件属性的设置,遍历文件夹,文件的简单读写,并且都给出示例代码。


1、File类简介与文件的创建、删除、重命名


主要内容包括File类,File类用来代表文件或文件夹,通过File类,可以对文件与文件夹执行丰富的操作,并且可以获取文件的路径、大小、文件名等信息;通过文件类的creatNewFile()方法创建文件,通过delete()方法删除文件,使用renameTo()方法重命名文件。

import java.io.File;
import java.io.IOException;

public class HelloFile {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		File file = new File("hello.txt");			//默认存在相对路径下,即该工程下
//		File file = new File("bin/hello.txt");		//文件存在于指定的绝对路径下
//		File file = new File("../hello.txt");		//文件存在于该工程路径的上一级
//		File file = new File("../../hello.txt");	//文件存在于该工程路径的上一级的上一级
		//判断文件是否存在
		if(file.exists())
		{
			//打印“文件”属性
			System.out.println(file.isFile());
			//打印“路径(文件夹)”属性
			System.out.println(file.isDirectory());
			
//			//同目录重命名
//			File nameto = new File("NewHello.txt");
//			file.renameTo(nameto);
			
//			//跨目录重命名
//			//注意1:文件夹结构必须处于同一个分区
//			//注意2:文件若处于不同的分区,需要使用文件的拷贝,而不是重命名
//			File nameto = new File("src/NewHello.txt");
//			file.renameTo(nameto);		
			
//			//删除文件
//			file.delete();
//			System.out.println("文件删除成功!");
		}
		else
		{
			System.out.println("文件不存在!");
			try {
				file.createNewFile();
				System.out.println("文件已经成功创建!");
			} catch (IOException e) {
				System.out.println("文件无法创建!");
			}
		}
	}

}



2、文件夹的创建、重命名、删除


主要内容包括通过使用mkdir()与mkdirs()方法创建文件夹,使用delete()方法删除文件夹,使用renameTo()方法重命名文件夹

import java.io.File;

public class HelloFolder {

	public static void main(String[] args) {
		//创建单级文件夹:folder.mkdir()
		File folder1 = new File("MyFolder1");
//		if(folder1.mkdir())
//		{
//			System.out.println("单级文件夹创建完成!");
//		}
//		else
//		{
//			if(folder1.exists())
//			{
//				System.out.println("单级文件夹已经存在,不用创建!");
//			}
//			else
//			{
//			System.out.println("单级文件夹创建失败!");
//			}
//		}
		
		//创建多级文件夹:folder.mkdirs()
		File folder2 = new File("MyFolder2/one/two");
//		if(folder2.mkdirs())
//		{
//			System.out.println("多级文件夹创建完成!");
//		}
//		else
//		{
//			if(folder2.exists())
//			{
//				System.out.println("多级文件夹已经存在,不用创建!");
//			}
//			else
//			{
//			System.out.println("多级文件夹创建失败!");
//			}
//		}
		
//		//文件夹重命名
//		//重命名同一级文件夹
//		File newfolder1 =new File("MyFolder3");
//		if(folder1.renameTo(newfolder1))
//		{
//			System.out.println("Done!");
//		}else{
//			System.out.println("Fail!");
//		}
//		//重命名不同级的文件夹,有点类似于移动,但仍归类于重命名
//		//注意:处于同一分区中
//		File newfolder2 =new File("MyFolder2/two");
//		if(folder2.renameTo(newfolder2))
//		{
//			System.out.println("Done!");
//		}else{
//			System.out.println("Fail!");
//		}
		
		//删除文件夹
		if(folder1.delete())
		{
			System.out.println("删除完成!");
		}else{
			System.out.println("删除失败!");
		}
//		//注意:只能删除空文件夹
//		folder2.delete();
	}

}



3、文件属性的读取


主要内容包括判断文件是否存在、文件名称、路径、文件大小、是否被隐藏、是否可读可写、是否为文件夹等。

import java.io.File;

public class ReadFileProperty {

	public static void main(String[] args) {
		File file = new File("text.txt");
		
		//判断文件是否存在
		System.out.println("文件是否存在"+file.exists());
		
		//读文件名称
		System.out.println("读取文件名称"+file.getName());
		
		//读取文件路径(相对路径)
		System.out.println("读取文件相对路径"+file.getPath());
		
		//读取绝对路径
		System.out.println("读取文件绝对路径"+file.getAbsolutePath());
		
		//读取文件父级路径
		System.out.println("读取文件父级路径"+file.getParent());//返回相对路径的上一级
		System.out.println("读取文件父级路径"+ new File(file.getAbsolutePath()).getParent());//返回绝对路径的上一级
		
		//读取文件大小
		System.out.println("读取文件大小"+file.length()+"byte");
		System.out.println("读取文件大小"+(float)file.length()/1000+"KB");
		
		//判断文件是否被隐藏
		System.out.println("判断文件是否被隐藏"+file.isHidden());
	
		//判断文件是否可读
		System.out.println("判断文件是否可读"+file.canRead());
		
		//判断文件是否可写
		System.out.println("判断文件是否可写"+file.canWrite());
		
		//判断文件是否为文件夹
		System.out.println("判断文件是否为文件夹"+file.isDirectory());
		
	}

}



4、文件属性的设置


主要内容包括将文件设定为可读、可写或只读。

import java.io.File;
import java.io.IOException;

public class SetFileProperty {

	public static void main(String[] args) {
		File file = new File("text.file");
		if(file.exists())
		{
			System.out.println("文件存在,不用创建!");
			
			//先确认文件的属性
			System.out.println("可读吗?"+file.canRead());
			System.out.println("可写吗?"+file.canWrite());
			System.out.println("可执行吗?"+file.canExecute());
			//将文件设定为可写
	//		file.setWritable(false);//true可写false不可写
			
			//将文件设定为可读
	//		file.setReadable(false);//true可读false不可读
			
			//将文件设定为只读
			file.setReadOnly();
			
			//再确认文件的属性
			System.out.println("\n");
			System.out.println("可读吗?"+file.canRead());
			System.out.println("可写吗?"+file.canWrite());
			System.out.println("可执行吗?"+file.canExecute());
			
		}else{
			System.out.println("文件不存在,请创建一个新文件!");
			try {
				file.createNewFile();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		
		
	}

}



5、遍历文件夹


主要内容包括通过使用listFiles()方法获取文件夹中的所有项目,并且通过递归显示完整的层级结构。

package com.hqu.filetraverse.main;

import java.io.File;

public class Traverse {

	public static void main(String[] args) {
		printFiles(new File("/Job/Java/workspace/FileTraverse"),1);//使用绝对路径
//		printFiles(new File("../FileTraverse"),1);//默认使用相对路径
	}
	
	public static void printFiles(File dir,int tab) {
		if(dir.isDirectory())
		{
			File next[] = dir.listFiles();		//返回值是文件和文件夹,存在于数组中
			for(int i=0;i<next.length;i++){
				for(int j=0;j<tab;j++){			//输出|--当做识别层次的标记
					System.out.print("|--");	//使用print而不是println,可以避免每次的换行
				}
				System.out.println(next[i].getName());//打印文件或文件夹的名字
				if(next[i].isDirectory()){
					printFiles(next[i],tab+1);	//递归调用自身
				}
			}
		}
	}

}



6、文件的简单读写


主要内容包括FileInputStream和FileOutputStream的使用方法,实现文本文件的读取和写出。

package com.hqu.rwfile;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;

public class ReadFile {

	public static void main(String[] args) {
		File file = new File("text.txt"); //事先创建好,并输入内容
		if(file.exists()){
//			System.out.println("exit");
			System.err.println("exit");//系统输出
			try {
				
				//准备用于文件输入的三个流
				FileInputStream fis = new FileInputStream(file);//文件的输入流属于字节流
				InputStreamReader isr = new InputStreamReader(fis, "UTF-8");//InputStreamReader属于字符流,"UTF-8"为指定文本编码,防止乱码
				BufferedReader br = new BufferedReader(isr);//带有缓冲区的Reader
				
				String line;	//用于临时存放读取到的数据
				while((line = br.readLine()) != null){
					System.out.println(line);
				}
				
				//关闭输入流
				br.close();
				isr.close();
				fis.close();
				
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} 
		}
		
		
		File newfile = new File("newtext.txt");//无需创建,写入时系统自动创建文件
		try {
			
			FileOutputStream fos = new FileOutputStream(newfile);
			OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
			BufferedWriter bw = new BufferedWriter(osw);
			
			bw.write("abcd\n");
			bw.write("efgh\n");
			bw.write("ijkl\n");
			bw.write("mnop");
//			bw.write("长歌行 汉乐府");
//			bw.write("青青园中葵,朝露待日晞。\n");
//			bw.write("阳春布德泽,万物生光辉。\n");
//			bw.write("常恐秋节至,焜黄华叶衰。\n");
//			bw.write("百川东到海,何时复西归?\n");
//			bw.write("少壮不努力,老大徒伤悲!\n");
			
			bw.close();
			osw.close();
			fos.close();
			
			System.out.println("写入完成!");
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值