繁体   English   中英

如何通过知道 position 从文件中删除一行?

[英]How to remove a line from a file by knowing its position?

我想从我的文件中删除一行(特别是第二行),所以我使用了另一个文件来复制它,但是使用以下代码,第二个文件包含完全相同的文本。(我的原始 file.txt 和我的最终文件.xml)

public static File fileparse() throws SQLException, FileNotFoundException, IOException {  
    File f=fillfile();//my original file
    dostemp = new DataOutputStream(new FileOutputStream(filetemp));
    int lineremove=1;
    while (f.length()!=0) {
        if (lineremove<2) {
            read = in.readLine();
            dostemp.writeBytes(read);     
            lineremove++;
        }

        if (lineremove==2) {
            lineremove++;
        }

        if (lineremove>2) {
            read = in.readLine();
            dostemp.writeBytes(read); 
        }
    }

    return filetemp;
}

如果lineremove为 2,则您不会读取该行,并且您在它为 2 时增加它之后检查它是否大于 2。这样做:

int line = 1;
String read = null;
while((read = in.readLine()) != null){
   if(line!=2)
   {
     dostemp.writeBytes(read);     
   } 
   line++;
}

您可以使用带有readLine()方法的BufferedReader逐行读取,检查它是否是您想要的行并跳过您不想要的行。

检查文档: BufferedReader

这是一个工作示例(不是最漂亮或最干净的:)):

    public static void main(String[] args) {
    // TODO Auto-generated method stub
    BufferedReader in = null;
    try {
        in = new BufferedReader(new FileReader("d:\\test.txt"));
    } catch (FileNotFoundException e3) {
        // TODO Auto-generated catch block
        e3.printStackTrace();
    }
    PrintWriter out = null ;
    try {
        out = new PrintWriter (new FileWriter ("d:\\test_out.txt"));
    } catch (IOException e2) {
        // TODO Auto-generated catch block
        e2.printStackTrace();
    }

    String line = null;
    int lineNum = 0;
    try {
        while( (line = in.readLine()) != null) {
            lineNum +=1;
            if(lineNum == 2){
                continue;
            }
            out.println(line);
        }
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    out.flush();

    out.close();
    try {
        in.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM