关于java怎么在文件的指定位置插入数据,而不覆盖指定位置后原有的数据?的问题
FileOperation是自定义的类来实现此功能J2SDK的API未提供此功能。
insert函数写了2个,一个是向文件尾加(最后一个),一个向指定位置加
import 。BufferedReader;
import 。File;
import 。
FileNotFoundException;
import 。FileOutputStream;
import 。FileReader;
import 。IOException;
public class Test {
private Test(String filePath, int index, String content) {
File f = new File(filePath);
FileOperation fo;
String errMsg = “”;
try {
fo = new FileOperation(f);
int error = sert(index, content);
switch (error) {
case 0:
errMsg = “OK”;
break;
case -1:
errMsg = “Output File Not Found!”;
break;
case -2:
errMsg = “Insert position too far”;
break;
}
intln(errMsg);
} catch (IOException e) {
intStackTrace();
}
}
public static void main(String[] args) {
Test t = new Test(“d:\\test。
txt”, 5, “abc”);
}
}
class FileOperation {
private StringBuffer sb = new StringBuffer();
private File orgFile = null;
public FileOperation(File f) throws IOException{
orgFile = f;
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(orgFile));
while ( ady()) {
sb。
append( adLine() + “\r\n”);
}
} catch (FileNotFoundException e) {
intStackTrace();
} finally {
ose();
br = null;
}
}
public int insert(int x, String str) throws IOException{
if (x > sb。
length()) {
return -2;
}
sert(x, str);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(orgFile);
fos。
write( String()。getBytes());
fos。flush();
} catch (FileNotFoundException e) {
intStackTrace();
return -1;
} finally {
ose();
fos = null;
}
return 0;
}
public int insert(String str) throws IOException{
sb。
append(str);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(orgFile);
fos。write( String()。
getBytes());
fos。
flush();
} catch (FileNotFoundException e) {
intStackTrace();
return -1;
} finally {
ose();
fos = null;
}
return 0;
}
}。