javaSE-day09--对文件夹和文件的基本操作、BufferedRead和BufferedWriter的基本用法、IO测试

本文介绍了如何使用Java进行基本的文件和文件夹操作,包括创建、删除、重命名文件及获取文件属性等常用方法,并通过示例代码展示了具体用法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

对文件夹和文件的基本操作

package day09;

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

/**
 * File是对一个文件或文件夹的 信息描述
 * File还提供了很多便利的工具方法: mkdirs创建文件夹   createNewFile创建新的空文件  getAbsolutePath:获取路径
 * getName 获取名称    isFile/isDirecotry 判断是文件还是文件夹     
 * exists判断该路径是否存在
 * 
 * @author ThinkPad
 *
 */
public class FileDemo {
	
	public static void main(String[] args) throws IOException {
		
		// 将路径描述成File对象
		File file = new File("d:/aaa/bbb/ccc");
		boolean exists = file.exists();   // 如果路径所表示的文件或者文件夹存在,则返回true
		
		// 判断该file是文件夹还是文件
		boolean directory = file.isDirectory();
		System.out.println(directory);   // true
		
		boolean ifFile = file.isFile();
		System.out.println(ifFile);  // false
		
		// 获取文件的绝对路径
		String absolutePath = file.getAbsolutePath();
		System.out.println(absolutePath);
		
		// 可以获取文件名或文件夹名
		String name2 = file.getName();
		System.out.println(name2);
		
		
		File file2 = new File("d:/pics/4beec3e3ly1fhfsr9hoa4j20m80xcn1r.jpg");
		ifFile  = file2.isFile();  // true
		
		// 获取文件名
		String name = file2.getName();
		System.out.println(name);
		
		// 获取上一级目录的file对象
		File parentFile = file2.getParentFile();
		System.out.println(parentFile.getAbsolutePath());
		
		// 获取上一级目录的路径字符串
		String parent = file2.getParent();
		System.out.println(parent);
		
		
		// 获取文件长度 字节(8个bit-- 二进制位)
		long length = file2.length();
		System.out.println(length);
		
		System.out.println("------------------------");
	
		// 获取指定目录下的子节点的名称字符串
		String[] list = file.list();
		for(String s:list) {
			System.out.println(s);
		}
		
		System.out.println("------------------------");
		
		// 获取指定目录下的子节点的File描述对象
		File[] listFiles = file.listFiles();
		for(File f:listFiles) {
			System.out.println(f.getAbsolutePath());
		}
		
		
		// 创建一个文件夹
		File f = new File("d:/xx/yy");
		boolean mkdir = f.mkdir(); // 不能创建多级目录
		System.out.println(mkdir);
		
		boolean mkdirs = f.mkdirs();  // 可以创建多级目录
		System.out.println(mkdirs);
		
		
		// 创建文件
		File file3 = new File("d:/xx/yy/cls.avi");
		boolean createNewFile = file3.createNewFile();
		System.out.println(createNewFile);
		
		// 重命名文件:其实可以把路径都给改了
		file3.renameTo(new File("d:/xx/yy/bdls.avi"));
		
		// 删除文件
		boolean delete = file3.delete();
		System.out.println(delete);
		
		
	}
	

}

字符输入

package day09;

import java.io.FileInputStream;
import java.io.IOException;

public class FileInputStreamDemo {

	public static void main(String[] args) throws IOException {
		//读取文件先构造一个FileInputStream对象
		FileInputStream fis = new FileInputStream("d:/a.txt");
		
		//FileInputStream是一种字节流,是按照字节一个一个的读取
	  /* int read = fis.read();
		 System.out.println(read);
		 
		  read = fis.read();
		 System.out.println(read);
		 
		 read = fis.read();
		 System.out.println(read);
		 
		 read = fis.read();
		 System.out.println(read);*/
		 //如果没有数了会返回-1
		 //利用这个特性wile循环来读
	/*	int read = 0;
		 while((read=fis.read())!=-1) {
			 char c = (char)read;   //读取字符要将数字根据码表转换--ASCII
			 System.out.println(c);
		 }*/
		 
		 /*
		  * 一次取多个然后字符 然后一次性转换
		  * read(buf)一次性读取buf个字节数据,读取的字节直接存取到but数组中
		  */
//		 byte[] buf = new byte[4]; //控制几个字节一读
//		 int num = fis.read(buf); //返回真实的读取到的字节数量
//		 String string = new String(buf); //将读取到的字节 转换成字符串 String(buf,0,7) 转换第0到之后7个字符
//		 System.out.println(num+","+string);
		 
		//用while来读取
		 int num = 0;
		 byte[] buf = new byte[8];
		 while((num=fis.read(buf))!=-1) {
			 System.out.println(new String(buf,0,num));//控制0-num(num=8,不包含第8个)个为一行
		 }
		 
		  fis.close();
	}

}

字符输出

package day09;


import java.io.FileOutputStream;

public class FileOutputDemo {
	public static void main(String[] args) throws Exception {
		// 覆盖的方式写入文件
		FileOutputStream fos = new FileOutputStream("d:/b.txt");
		String a = "hellow";
		byte[] bs = a.getBytes("UTF-8");
		fos.write(bs);
		fos.close();

		// 追加的方式写入文件,需要多加一个true

		FileOutputStream fos2 = new FileOutputStream("d:/b.txt", true);
		String aa = ",你好啊";
		byte[] bs2 = aa.getBytes("UTF-8");
		fos2.write(bs2);
		fos2.close();

	}
}

读取一行

package day09;

import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class ReadLine {
	public static void main(String[] args) throws Exception {
		FileInputStream fis = new FileInputStream("d:/a.txt");
		int read = 0;
		byte[] buf = new byte[1024]; //这个数组用来存放每次读取到的数字
		int i = 0;
		while((read=fis.read())!=-1) { //逐个数字读取
			if(read==14) {  //当遇到空格时就结束本次循环
				break;        
			}
			buf[i] = (byte)read; //这里存储的是数字 不是字母
			i++;
		}
		System.out.println(new String(buf,0,i)); //将数字转换成字母
	 fis.close();
	}
		
}

文件中的单词统计—HashMap

package day09;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;

public class FileWordcount {
	public static void main(String[] args) throws Exception, FileNotFoundException {
		BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("d:/a.txt"), "UTF-8"));
		String line = "";
		HashMap<String, Integer> hashMap = new HashMap<>();
		while ((line = br.readLine()) != null) { // 先按行读取
			String[] split = line.split(" "); // 把读取的每一行按空格切割 存入数组

			for (String word : split) { // 遍历数组
				if (hashMap.containsKey(word)) { // 看hashmap中是否存在该单词
					hashMap.put(word, hashMap.get(word) + 1); // 存在则value+1
				} else {
					hashMap.put(word, 1); // 不存在则加入该单词value为1
				}
			}
		}
		br.close();
		// 遍历hashmap
		Set<Entry<String, Integer>> entrySet = hashMap.entrySet();
		for (Entry<String, Integer> a : entrySet) {
			System.out.println(a.getKey() + " : " + a.getValue());
		}

	}
}

最常用的两个工具—BufferedRead和BufferedWriter

输入

package day09;

import java.io.BufferedReader;

import java.io.FileInputStream;

import java.io.InputStreamReader;
/*
 * FileInputStream的一个高级包装工具BufferedReader
 * 它可以按照文本来读取,也可以按行读取
 * 
 */
public class BufferedReadDemo {
	public static void main(String[] args) throws Exception {
		//BufferReader包装了字节流,并且可以按照指定的编码集将字节转换成字符   
		BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("d:/a.txt"),"UTF-8"));
		//按行读取
		String line = br.readLine();
		System.out.println(line);
		
		line = br.readLine();
		System.out.println(line);
		System.out.println("---------------");
		//用while读取所有行
		while((line = br.readLine())!=null) {
			System.out.println(line);
		}
		
		br.close();

	}
}

输出

package day09;

import java.io.BufferedWriter;

import java.io.FileOutputStream;
import java.io.OutputStreamWriter;

public class BufferedWriteStreamDemo {
		public static void main(String[] args) throws Exception {
			BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("d:/c.txt",true),"UTF-8")); //true追加添加
			bw.write("你好啊,\r\n");//在Windows中换行需要\r\n linux 只需要\n
			bw.write("啊啊啊");		
			bw.close();
		}
}

IO 在应用的的测试

Product类

package day09.IODemo;

public class Product {
	private String Id;
	private String Name;
	private int num;

	public Product() {
	}

	public Product(String id, String name, int num) {
		Id = id;
		Name = name;
		this.num = num;
	}

	public String getId() {
		return Id;
	}

	public void setId(String id) {
		Id = id;
	}

	public String getName() {
		return Name;
	}

	public void setName(String name) {
		Name = name;
	}

	public int getNum() {
		return num;
	}

	public void setNum(int num) {
		this.num = num;
	}

	@Override
	public String toString() {
		return Id + "," + Name + "," + num;
	}

}

menu类

package day09.IODemo;

import java.util.ArrayList;
import java.util.Scanner;

public class Menu {
	public static void main(String[] args) throws Exception {
		boolean flag = true;
		Scanner sc = new Scanner(System.in);
		ProductDao dao = new ProductDaoImpl();  //使用接口中的功能
		while(flag) {
			System.out.println("1.添加商品  2.查看商品  3.退出");
			String Line = sc.nextLine();
			switch(Line) {
			case "1":
				System.out.println("输入商品信息:(例如:1,苹果,5)");
				String nextLine = sc.nextLine();
				dao.addProduct(nextLine);	
				break;
			
			case "2":
				ArrayList<Product> allproduct = dao.getAllproduct();
				for(Product ss:allproduct) {
					System.out.println(ss);
					}
				break;
			case "3":
				flag = false;
				System.out.println("退出成功!");
				break;
			default:
				System.out.println("重新输入!");
				break; 
			}
		}
	}
}

功能接口

package day09.IODemo;

import java.util.ArrayList;

public interface ProductDao {
	public void addProduct(String Line) throws Exception; //添加商品
	public ArrayList<Product> getAllproduct() throws Exception;//返回list对象
}

添加功能和查询功能的实现—在文件中

package day09.IODemo;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;

public class ProductDaoImpl implements ProductDao {

	@Override
	public void addProduct(String Line) throws Exception {
		
		BufferedWriter bw = new BufferedWriter(
				new OutputStreamWriter(new FileOutputStream("d:/aa.txt", true), "UTF-8"));
				//true表示追加添加
																				
		bw.write(Line + "\r\n"); //换行Windows中用/r/n  linux 用/n
		bw.close();	//关流
	}

	@Override
	public ArrayList<Product> getAllproduct() throws Exception {
		ArrayList<Product> pt = new ArrayList<>(); //生成list,最后返回该list
		BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("d:/aa.txt"),"UTF-8"));
		String a = "";
		while((a = br.readLine())!=null) { //读取完再读得到null
			String[] split = a.split(","); //按,字符切割
			Product product = new Product(split[0],split[1],Integer.parseInt(split[2]));
			//将字符转换成int
			pt.add(product);
		}
		br.close();
		return pt;
	}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值