java代码写入文件的方法大全

戚薇 Java经验 发布时间:2023-07-02 20:13:11 阅读数:4373 1
下文笔者讲述写入文件的方法大全,如下所示

写入文件的实现思路

写入文件的实现思路
    借助FileOutputStream
	然后向outputStream中写入字节数组
	   或
	     写入字符串

写入数据byte[]
而不只是文本
直接使用FileOutputStream

/**
 * 保存文件数据
 * 
 * @param file 文件对象
 * @param data 文件数据
 */
public static void save(File file, byte[] data) {
	try (OutputStream out = new FileOutputStream(file)) {
		out.write(data);
		out.flush();
	} catch (IOException e) {
		LOGGER.warning(e);
	}
}

字符串写入到文本的方法

/**
 * 保存文本文件
 * 
 * @param file 文件对象
 * @param text 文本内容
 */
public static void saveTextOld(File file, String text) {
	LOGGER.info("正在保存文件{0}, 保存内容:\n{1}", file.toString(), text);

	try (OutputStream out = new FileOutputStream(file);) {
		bytes2output(out, text.getBytes(StandardCharsets.UTF_8));
	} catch (IOException e) {
		LOGGER.warning(e);
	}
}

写入文件的新方法

使用Files.write()方法保存数据
/**
 * 保存文件数据
 * 
 * @param file        文件对象
 * @param data        文件数据
 * @param isOverwrite 是否覆盖文件
 */
public static void save(File file, byte[] data, boolean isOverwrite) {
	LOGGER.info("正在保存文件" + file);

	try {
		if (!isOverwrite && file.exists())
			throw new IOException(file + "文件已经存在,禁止覆盖!");

		if (file.isDirectory())
			throw new IOException(file + " 不能是目录,请指定文件");

		if (!file.exists())
			file.createNewFile();

		Files.write(file.toPath(), data);
	} catch (IOException e) {
		LOGGER.warning(e);
	}
}

保存文本文件

/**
 * 保存文本内容
 * 
 * @param file 文件对象
 * @param text 文本内容
 */
public static void saveText(File file, String text) {
	if (Version.isDebug) {
		String _text = text.length() > 200 ? text.substring(0, 200) + "..." : text;
		LOGGER.info("正在保存文件{0}, 保存内容:\n{1}", file.toString(), _text);
	} else
		LOGGER.info("正在保存文件{0}, 保存内容:\n{1}", file.toString());

	save(file, text.getBytes(StandardCharsets.UTF_8), true);
}

保存文本内容

/**
 * 保存文本内容
 * 
 * @param filePath 文件路径
 * @param text     文本内容
 */
public static void saveText(String filePath, String text) {
	saveText(new File(filePath), text);
}
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaJingYan/202307/16883000296963.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者