java读取文件写入文件删除文件

此博客主要围绕Java进行文件读写操作展开,虽未给出具体内容,但核心是利用Java语言实现文件的读取与写入功能,属于后端开发中文件处理的常见操作。

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

/**
 * ClassName:FileUtil.java
 * Date:2017年2月24日
 */
package com.hndist.tsps.tool;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Creater: ShaoGaige
 * Description:文件读取写入类
 * Log:
 */
public class FileUtil {
	
	/**
	 * 根据路径读取文件成byte数组
	 * @param path
	 * @return byte[]
	 */
	public static byte[] readFile(String path)
	{
		try 
		{
			FileInputStream file = new FileInputStream(path);
			BufferedInputStream in = new BufferedInputStream(file);
			ByteArrayOutputStream out = new ByteArrayOutputStream(1024*1024);
			byte[] temp = new byte[1024*1024];     
	        int size = 0;     
	        while ((size = in.read(temp)) != -1) 
	        {     
	            out.write(temp, 0, size);     
	        }     
	        in.close();     
	        byte[] content = out.toByteArray();
	        
	        return content;
			
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * 写入文件
	 * @param path
	 * @param content
	 */
	public static void writeFile(String path,byte[] content)
	{
		
	    try 
	    {
	    	
	    	File file = new File(path);
	    	File dir = new File(file.getParent());
			if (!dir.exists()) {
				dir.mkdirs();
			}
	    	FileOutputStream fos = new FileOutputStream(path);
			fos.write(content);
			fos.close(); 
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	/**
	 * 写入文件2
	 * @param path
	 * @param content
	 */
	public static void writeFile(String path,String  body)
	{
	try{
			
			PrintStream mytxt=new PrintStream(path);
			PrintStream out=System.out;
			System.setOut(body);
			}catch(FileNotFoundException e){
			
			e.printStackTrace();

		}
	}
	/**
	 * 删除文件
	 * @param file
	 * @return
	 */
	public static boolean delFile(File file)
	{
		if(file == null)
		{
			return false;
		}
		//File file = new File(path);
		if (!file.exists()) {
		    return false;
		}
		 
		if (file.isDirectory()) {
		    File[] files = file.listFiles();
		    for (File f : files) {
		        delFile(f);
		    }
		}
		return file.delete();
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值