加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Android之文件读写工具类

发布时间:2020-12-14 23:17:07 所属栏目:Java 来源:网络整理
导读:今天PHP站长网 52php.cn把收集自互联网的代码分享给大家,仅供参考。 本类主要功能有: import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;/** * 文件读写工具类 * * @author bear *

以下代码由PHP站长网 52php.cn收集自互联网

现在PHP站长网小编把它分享给大家,仅供参考

本类主要功能有:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

/**
 * 文件读写工具类
 * 
 * @author bear
 *
 */
public class FileUtil {

	/**
	 * 如果文件不存在,就创建文件
	 * 
	 * @param path 文件路径
	 * @return
	 */
	public static String createIfNotExist(String path) {
		File file = new File(path);
		if (!file.exists()) {
			try {
				file.createNewFile();
			} catch (Exception e) {
				System.out.println(e.getMessage());
			}
		}
		return path;
	}

	/**
	 * 向文件中写入数据
	 * 
	 * @param filePath
	 *            目标文件全路径
	 * @param data
	 *            要写入的数据
	 * @return 0表示成功写入,1表示没找到文件,2表示IO异常
	 */
	public static boolean writeBytes(String filePath,byte[] data) {
		try {
			FileOutputStream fos = new FileOutputStream(filePath);
			fos.write(data);
			fos.close();
			return true;
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
		return false;
	}

	/**
	 * 从文件中读取数据
	 * 
	 * @param file
	 * @return
	 */
	public static byte[] readBytes(String file) {
		try {
			FileInputStream fis = new FileInputStream(file);
			int len = fis.available();
			byte[] buffer = new byte[len];
			fis.read(buffer);
			fis.close();
			return buffer;
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}

		return null;

	}

	/**
	 * 向文件中写入字符串String类型的内容
	 * 
	 * @param file
	 *            文件路径
	 * @param content
	 *            文件内容
	 * @param charset
	 *            写入时候所使用的字符集
	 */
	public static void writeString(String file,String content,String charset) {
		try {
			byte[] data = content.getBytes(charset);
			writeBytes(file,data);
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}

	}

	/**
	 * 从文件中读取数据,返回类型是字符串String类型
	 * 
	 * @param file
	 *            文件路径
	 * @param charset
	 *            读取文件时使用的字符集,如utf-8、GBK等
	 * @return
	 */
	public static String readString(String file,String charset) {
		byte[] data = readBytes(file);
		String ret = null;

		try {
			ret = new String(data,charset);
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
		return ret;
	}

}

以上内容由PHP站长网【52php.cn】收集整理供大家参考研究

如果以上内容对您有帮助,欢迎收藏、点赞、推荐、分享。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读