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();
}
}
}