向文件写入内容、修改文件内容。JAVA

本文深入讲解了使用Java进行文件操作的方法,包括如何向文件添加内容和如何修改文件内容。通过具体的代码示例,展示了如何使用FileOutputStream和FileInputStream类来实现文件的读写功能。
package xyz.jangle.file.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/** 
* @author jangle E-mail: jangle@jangle.xyz
* @version 2018年10月21日 上午10:08:11 
* 类说明 
*/
public class OutputStreamTest {

	public static void main(String[] args) {
		testOutput();
		testInsertFile();
	}
	
	/**
	 * 向文件添加内容
	 */
	private static void testOutput() {
		String path = "d:/logs/zjoa/a/a/";
		String fileName = "exchange.txt";
		File filePath = new File(path);
		if(!filePath.exists()) {
			filePath.mkdirs();
		}
		File file = new File(path+fileName);
		try {
			FileOutputStream out = new FileOutputStream(file,true);	//第二个参数表示是否添加
			//不添加第二个参数时候,将对文件进行重写(即默认false)
			out.write((" \n测试文本内容的输出2 \n</beans>").getBytes());
			out.flush();
			out.close();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		System.out.println("ok");
	}
	/**
	 * 修改文件内容
	 */
	private static void testInsertFile() {
		String path = "d:/logs/zjoa/a/a/";
		String fileName = "exchange.xml";
		File filePath = new File(path);
		if(!filePath.exists()) {
			filePath.mkdirs();
		}
		File file = new File(path+fileName);
		try {
			FileInputStream in = new FileInputStream(file);
			byte[] b = new byte[in.available()];
			in.read(b);
			in.close();
			String content = new String(b);
			System.out.println(content);
			int indexOf = content.indexOf("</beans>");
			System.out.println(indexOf);
			String insertStr = "		<action name=\"oaDemoAction\" class=\"com.xxxx.action.OaDemoAction\">\r\n" + 
					"			<result name=\"success\" type=\"json\">\r\n" + 
					"				<param name=\"root\">dataMap</param>\r\n" + 
					"			</result>\r\n" + 
					"		</action>";
			insertStr += "\n</beans>";
//			content.replace("</beans>", insertStr);
			String newContent = content.substring(0, indexOf);
			newContent = newContent + insertStr;
			FileOutputStream out = new FileOutputStream(file,false);	//第二个参数表示是否添加
			//不添加第二个参数时候,将对文件进行重写(即默认false)
			out.write(newContent.getBytes());
			out.flush();
			out.close();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
	}

}

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值