我想从我的文件中删除一行(特别是第二行) 所以我使用了另一个文件进行复制,但使用下面的代码,第二个文件包含完全相同的文本。(我的原始文件.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;
}
答案 0 :(得分:5)
如果lineremove
为2,则不会读取该行,并且在您将其增加为2时检查它是否大于2.请执行以下操作:
int line = 1;
String read = null;
while((read = in.readLine()) != null){
if(line!=2)
{
dostemp.writeBytes(read);
}
line++;
}
答案 1 :(得分:2)
您可以使用BufferedReader
和readLine()
方法逐行阅读,检查它是否是您想要的行,并跳过您不想要的行。
查看文档:{{3}}
这是一个工作示例(不是最漂亮或最干净:) :):
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();
}
}