往文件里添加一个字符串

package com.tulun;

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

/**  
* 描述:往文件里添加一个字符串
*  
* @author ASUS  
* @date 2018年8月4日
*/
public class TestGY2 {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		takeConTentsToFile("D:/雷克塞.txt",4,"从来不会想");
	}
	public static void takeConTentsToFile(String filePath,int pos,String contents) {
		//参数校验
		File file = new File(filePath);
        if(!(file.exists()&&file.isFile())) {
    	   System.out.println("文件不存在");
        }
        if(pos<0||pos>file.length()) {
        	System.out.println("pos不合法");
        }
        try {
        	//创建临时文件
			File tempFile=File.createTempFile("kkkkkkkkk", ".temp",new File("D:/"));
			FileOutputStream fileOutputStream = new FileOutputStream(tempFile);
			FileInputStream fileInputStream = new FileInputStream(tempFile);
			tempFile.deleteOnExit();
			//实例化RandomAccessFile对象,实现题目
			RandomAccessFile randomAccessFile = new RandomAccessFile(file,"rw");
			randomAccessFile.seek(pos);
			int len = 0;
			while((len = randomAccessFile.read())!=-1) {
				randomAccessFile.write(len);
			}
			randomAccessFile.seek(pos);
			randomAccessFile.write(contents.getBytes());
			while((len = fileInputStream.read()) !=-1) {
				randomAccessFile.write(len);
			}
			randomAccessFile.close();
			fileInputStream.close();
			fileOutputStream.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
	}
	
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值