开发者

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

I want to remove a line from my file (specifically the second line) so I have used another file to copy in it ,but using the following code the second file contain exactly the same text.(My original file .txt and my final fil开发者_如何学Pythone .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;
}


You do not read the line if the lineremove is 2 and also you check if it is greater than 2 after you increased it when it was 2. Do it like this:

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


you can use BufferedReader with the readLine() method to read line by line, check if it a line you want and skip the lines you dont want.

check the docs at: BufferedReader

here is a working example (Not the most beautiful or clean :) ):

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

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜