java jINSERT test.out 9 "hello world"
will insert the string "hello world" at line number 9 in the file "test.out".
of course you need more error checking... [JDK1.1]
import java.io.*; public class jINSERT {
public static void main(String args[]){
try {
jINSERT j = new jINSERT();
j.insertStringInFile
(new File(args[0]),Integer.parseInt(args[1]), args[2]);
}
catch (Exception e) {
e.printStackTrace();
}
} public void insertStringInFile(File inFile, int lineno, String lineToBeInserted)
throws Exception {
// temp file
File outFile = new File("$$$$$$$$.tmp");
// input
FileInputStream fis = new FileInputStream(inFile);
BufferedReader in = new BufferedReader
(new InputStreamReader(fis)); // output
FileOutputStream fos = new FileOutputStream(outFile);
PrintWriter out = new PrintWriter(fos); String thisLine = "";
int i =1;
while ((thisLine = in.readLine()) != null) {
if(i == lineno) out.println(lineToBeInserted);
out.println(thisLine);
i++;
}
out.flush();
out.close();
in.close();
inFile.delete();
outFile.renameTo(inFile);
}
}
will insert the string "hello world" at line number 9 in the file "test.out".
of course you need more error checking... [JDK1.1]
import java.io.*; public class jINSERT {
public static void main(String args[]){
try {
jINSERT j = new jINSERT();
j.insertStringInFile
(new File(args[0]),Integer.parseInt(args[1]), args[2]);
}
catch (Exception e) {
e.printStackTrace();
}
} public void insertStringInFile(File inFile, int lineno, String lineToBeInserted)
throws Exception {
// temp file
File outFile = new File("$$$$$$$$.tmp");
// input
FileInputStream fis = new FileInputStream(inFile);
BufferedReader in = new BufferedReader
(new InputStreamReader(fis)); // output
FileOutputStream fos = new FileOutputStream(outFile);
PrintWriter out = new PrintWriter(fos); String thisLine = "";
int i =1;
while ((thisLine = in.readLine()) != null) {
if(i == lineno) out.println(lineToBeInserted);
out.println(thisLine);
i++;
}
out.flush();
out.close();
in.close();
inFile.delete();
outFile.renameTo(inFile);
}
}
解决方案 »
- Java 求惑
- java 数组下标返回
- 今天无聊再温习think in Java 发现一个问题
- 最近点背,散分
- 如何在javabean中获取页面的内置对象application呢?
- 关于皮肤设置的问题
- [200分]如何动态给通过LocateRegistry.createRegistry(动态端口);建立一个端口注册,预防和已注册的端口冲突(因为多个LocateRegist
- log4j 如何通过配置文件实现日志信息入库,不写代码只是写配置文件?????
- java socket采用多线程接收数据出现CPU使用上升的问题
- JAVA中怎样捕捉计算机SYSTEM的句柄??
- 請問幾個在Applet中處理文字的問題
- 那里有MYSQL的JDBC驱动程序
往write.txt文件里写入,如果遇到指定的值就多写入一行要写入的值。