JAVA What am I doing wrong, I want the line [closed]

拟墨画扇 提交于 2020-01-15 12:06:13

问题


I am trying to make a change log and so I need a single line between some sentences. All I have is this but it doesn't seem to work. Can anyone help me please?

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

回答1:


The problem that you might be encountering might be because of the "line separator" used by the BufferedWriter (it gets set when you create said class). I think it would be best to use instead:

System.getProperty("line.separator");

This way you use the System's line separator rather than a hard coded one.

So that your code would look like this:

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

I will try to be as brief and clear as possible.

I assume that you are opening a file that in my code I call "test.txt" and it's got about a paragraph or so. And that you want that outputted to another file, but with "empty lines" at some points.

Because File() is read line by line, it is much easier to open your main file read a line, and then write it to your log file, then analyse if an empty line is necessary and place it.

Let's see some code then.

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

One of the big differences from this code is that I only open the files once, while in your code you open the log file every time you want to add a new file. You should read the documentation, so you'll know that every time you open the file, your cursor is pointing to the first line, so anything you add will be added to first line.

I hope this helped you understand some more.




回答2:


I'm not totally sure what you are asking for, but have you tried setting the "append" flag on true, so the FileWriter will not start a new file, but append content to it at the end? This is done by calling the FileWriter(File, boolean) constructor:

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:


I need a single line between some sentences

I guess you mean a new line between other lines of the same file.

To do so you have to read the whole file, locate the place where you want to insert a line, insert the line then write the new content to the file.

This should work fine for small files but if you have large files you might get in trouble.

So you need a more scaleable way of doing it: Read line by line, and write write to a temp file. if you indentify the location where a new line should be inserted, write that line. Continue with the rest of the file. After you are done delete the original file and rename the temp file with the original name.

Pseudocode:

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

Code example: (unlike the pseudo code, the new line is inserted after)

Here the line "New Line!" is inserted after each line which is equal to "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);
    }
}

Note that File#delete() and File#renameTo both return a boolean value that is true onyl if the operation was successfull. You absolutely need to check those retuned values and handle accordingly.




回答4:


out.println("\n");

(instead of out.newLine();)

\n in java declares a new line. If you dont add any text before it then it should just print a blank line like you want.




回答5:


This will work Correctly.

Suggestion:

out.close(); and stream.close(); should write inside finally block ie they should close even if some exceptions occured.



来源:https://stackoverflow.com/questions/20637341/java-what-am-i-doing-wrong-i-want-the-line

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!