JAVA我做错了什么,我想要这条线

时间:2013-12-17 14:54:06

标签: java file line

我正在尝试更改日志,因此我需要在一些句子之间添加一行。 我只有这个,但似乎没有用。有人可以帮帮我吗?

@Test
public void addLine() {
    File temp;
    try {
        temp = File.createTempFile("app.log", ".tmp", new File("."));
        File appLog = new File("app.log");
        try (BufferedWriter bw = new BufferedWriter(new FileWriter(temp));
                BufferedReader br = new BufferedReader(new FileReader(
                        appLog))) {
            String line;
            while ((line = br.readLine()) != null) {
                bw.write(line);
                bw.newLine();
                if ("2 A".equals(line)) {
                    bw.write("New Line!");
                    bw.newLine();
                }
            }
            appLog.delete();
            temp.renameTo(appLog);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

5 个答案:

答案 0 :(得分:2)

您可能遇到的问题可能是由于BufferedWriter使用的“行分隔符”(它在您创建所述类时设置)。我认为最好使用:

System.getProperty("line.separator");

这样您就可以使用系统的行分隔符而不是硬编码分隔符。

这样你的代码就像这样:

    public void addLine() {
       String lineseparator=System.getProperty("line.separator");
   // I'd suggest putting this as a class variable, so that it only gets called once rather
   // than
   // everytime you call the addLine() method
    try {
        FileWriter stream = new FileWriter(this.log, true);
        //If you don't add true as the second parameter, then your file gets rewritten
       // instead of appended to
        BufferedWriter out = new BufferedWriter(stream);

        out.write(lineseparator); //This substitutes your out.newline(); call

       out.close();
       stream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
################################################## ############################。

我会尽量简短明了。

我假设您正在打开一个文件,在我的代码中我称之为“test.txt”并且它有一个左右的段落。并且你想要输出到另一个文件,但在某些点有“空行”。

因为逐行读取文件() ,所以打开主文件读取一行更容易,然后将其写入日志文件,然后分析是否需要空行放置它。

让我们看看一些代码。

// Assume you have a private class variable called
private String lineseparator=System.getProperty("line.separator");

// This method is in charge of calling the method that actually carries out the 
// reading and writing. I separate them both because I find it is much cleaner
// to have the try{}catch{} blocks in different methods. Though sometimes for
// logging purposes this is not the best choice
public void addLines() {
    try {
        readAndWrite();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

// This method is in charge of reading one file and output to another. 
public void readAndWrite() throws IOException {
    File test = new File("test.txt");
 FileWriter writer = writer = new FileWriter(new File("log.txt"), true);
     //This FileWriter is in charge of writing to your log file

 String line;
 boolean conditionToWriteNewLine=true;
      //Obviously this needs to be changed to suit your situation
      // I just added it for show

 BufferedReader reader = new BufferedReader( new FileReader (test));
 BufferedWriter out = new BufferedWriter(writer);

     //It is in this while loop that you read a line
     // Analyze whether it needs to have a new line or not
    // and then write it out to log file
 while( ( line = reader.readLine() ) != null ) {
        out.write(line); 
        if(conditionToWriteNewLine){
           out.write(this.lineseparator); 
           out.write(this.lineseparator);
               //You need to write it twice for an EMPTY LINE
        }     
 }
 reader.close();
 out.close();   
 }

与此代码的一个重大区别是,我只打开文件一次,而在您的代码中,每次要添加新文件时都会打开日志文件。您应该阅读文档,因此您将知道每次打开文件时,光标都指向第一行,因此您添加的任何内容都将添加到第一行。

我希望这有助于你了解更多。

答案 1 :(得分:1)

  

我需要在一些句子之间加一行

我猜你的意思是同一个文件的其他行之间的新行。

为此,您必须阅读整个文件,找到要插入行的位置,插入行然后将新内容写入文件。

这应该适用于小文件,但如果你有大文件,你可能会遇到麻烦。

因此,您需要一种更可扩展的方法:逐行读取,并将写入写入临时文件。如果您确定应插入新行的位置,请写入该行。继续文件的其余部分。完成后删除原始文件并使用原始名称重命名临时文件。

伪代码:

Open actual file
Open temp file
while not end of actual file
    Read one line from actual file
    Check if new line has to inserted now
        Yes:  write new line to temp
    write line from actual to temp
Close actual file
Close temp file
Delete actual
Rename temp to actual

代码示例:(与伪代码不同,后面插入新行)

此处在每行等于"New Line!"之后插入行"2 A"

@Test
public void insertNewLineIntoFile() throws IOException {
    File temp = File.createTempFile("app.log", ".tmp", new File("."));
    File appLog = new File("app.log");
    try (BufferedWriter bw = new BufferedWriter(new FileWriter(temp)); 
            BufferedReader br = new BufferedReader(new FileReader(appLog))) {
        String line;
        while((line = br.readLine()) != null) {
            bw.write(line);
            bw.newLine();
            if("2 A".equals(line)) {
                bw.write("New Line!");
                bw.newLine();
            }
        }
        appLog.delete();
        temp.renameTo(appLog);
    }
}

请注意,如果操作成功,File#delete()File#renameTo都返回一个真值为on的布尔值。您绝对需要检查这些重新调整的值并进行相应处理。

答案 2 :(得分:1)

我不完全确定你要求的是什么,但你是否尝试将“append”标志设置为true,因此FileWriter不会启动新文件,但会在最后添加内容?这是通过调用FileWriter(File, boolean)构造函数来完成的:

public void addLine() {
    try {
        FileWriter stream = new FileWriter(this.log, true); // Here!
        BufferedWriter out = new BufferedWriter(stream);

        out.write("New Extra Line Here");
        out.newLine();

        out.close();
        stream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

答案 3 :(得分:0)

通过out.println( “\ n”);

(而不是out.newLine();)

java中的

\ n声明了一个新行。如果你之前没有添加任何文字,那么它应该只是打印一个你想要的空白行。

答案 4 :(得分:0)

这将正常工作。

<强>建议:

out.close();stream.close();应在finally块内写入,即使发生了一些异常,它们也应该关闭。