自己创建一个文本文件为record.txt后,写入了如下两行数据:
00 11 33 33 44 
55 66 77 88 99
然后要把第一个出现的“33”改成符合顺序的“22”.
用代码怎么改呢??

解决方案 »

  1.   

    执行下面程序:record1.txt为lz所要的结果。import java.io.*;public class BufferedReaderTest {
    public static void main(String[] args) {
    BufferedReader br = null;
    InputStreamReader isr = null;
    FileInputStream fis = null; BufferedWriter bw = null;
    OutputStreamWriter osw = null;
    FileOutputStream fos = null; try {
    fis = new FileInputStream("D:\\record.txt");
    isr = new InputStreamReader(fis);
    br = new BufferedReader(isr); fos = new FileOutputStream("D:\\record1.txt");
    osw = new OutputStreamWriter(fos);
    bw = new BufferedWriter(osw); String str = null;
    int i = 0;
    while ((str = br.readLine()) != null) {
    String[] ss = str.split(" ");
    if (i == 0) {
    for (String s : ss) {
    // 避免一行中出现多个33
    if ("33".equals(s) && i == 0) {
    str = str.replaceFirst("33", "22");
    i++;
    }
    }
    }
    bw.write(str);
    bw.newLine();
    bw.flush();
    } } catch (IOException e) {
    e.printStackTrace();
    } finally {
    try {
    bw.close();
    osw.close();
    fos.close();
    br.close();
    isr.close();
    fis.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    } }
    }
      

  2.   

    是的,如果用 RandomAccessFile 也可以回去的,但是很麻烦,得判断换行符,得不偿失。从头一行一行地读的话,速度是非常快的。PS:为什么不先读 80 行,再读 100 行呢?奇怪,一定要先读完 100 行,再去读 80 行么?
      

  3.   

    不能读入textfield之类的控件内修改吗??
      

  4.   

    能不能在文本record.txt中修改里边的内容
    例如:abcde@123@,我只要修改两个@里边的内容