开发者

Remove extra lines in a text file

I would like to remove an extra line at the front of the text file that's being created for some reason. Here's the code for what I'm doing:

String line;
开发者_开发问答while ((line = textReader.readLine()) != null) {
   if (!line.contains("//")) textData.add(line);
   Pattern pattern = Pattern.compile("//.*$", Pattern.DOTALL);
   Matcher matcher = pattern.matcher(line);
   line = matcher.replaceFirst("");

If I remove the if (!line.contains("//")) textData.add(line); then the lines are not being outputted. Here's what I use to invoke writing method:

     WriteToFile filetoo = new WriteToFile("/Users/John/Desktop/newtext.txt", true);
            filetoo.write(anyLines[i]);

I want to start from the very first line and start writing to the file. Here's what my file looks like:

................. // blank space (I want to get rid of this)
line 1
line 2
line 3

Though I want it to look like this:

line 1
line 2
line 3

Any suggestions?


You could check if the line is "empty" and skip it - if (line.trim().length() != 0) should tell you if the line is not "blank".


SO it is not a blank line and instead matches the RE /^\s*\/\/.*/?

The RE I quoted should work, of if you are not using the / command, "^\s*//.*"

If it is blank, perhaps something like this:

[edit]

first = 1;
while ((line = textReader.readLine()) != null) {
  if (first)
   {
     if (matchera.matches("\s*$", line))
     {
        continue;
     }
     first = 0;
   }
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜