java初新手,隔行問題

本帖最後由 kstse2002 於 2010-11-16 21:05 編輯

點解會每句PRINT出來隔多左行
public class writefile{
String fileName = "C:\\output.txt";
String line;

                String word = "";
        public static void main(String args[]) {
                try {

                        BufferedReader in = new BufferedReader(new FileReader(fileName));
                        line = in.readLine();
                        while (line != null) { // continue until end of file
                                word += line + "\n";
                                line = in.readLine();
                        }
                        in.close();
                } catch (IOException iox) {
                }
pirnt(word);
}}

貼曬成個program code黎睇下~

TOP

This is not a good programming style because there are too many temporary string objects.  Take a look at:

Reader.read(char[] cbuf)
StringBuilder.append(char[] str, int offset, int len)

Also, you did not specify the character encoding in the constructor of FileReader().

As for your original question, I think you are in a mixed DOS/Unix EOL environment.

TOP

點解會每句隔多左行
public class writefile{
String fileName = "C:\\output.txt";
String line;

                Strin ...
kstse2002 發表於 2010-11-16 17:09



word += line+"\n";
word += "this is a line of text\n" + "\n";

TOP

word += line+"\n";
word += "this is a line of text\n" + "\n";
tonyli1212 發表於 2010-11-16 19:40

這兩句好似無咩分別,仲有PRINT你寫果句"This is a line of text"

TOP

這兩句好似無咩分別,仲有PRINT你寫果句"This is a line of text"
kstse2002 發表於 2010-11-16 21:06



    ..
i am not correct the error, but i am locate the error.....


think about if the value of line is "this is a line of text\n",
after you +"\n" at the end...
the value of word will become wt?

TOP

本帖最後由 kstse2002 於 2010-11-16 21:34 編輯

it will be two of the word  why the line  have "\n" inside, I only read the line , when I reemove "\n" , I cannot  wirte text by next line

TOP

it will be two of the word  why the line  have "\n" inside, I only read the line , when I reemove " ...
kstse2002 發表於 2010-11-16 21:20



原來readLine()唔會return埋個\n,
sorry,我記錯左…

TOP

                        line = in.readLine();
                        while (line != null) { // continue until end of file
                                word += line + "\n";
                                line = in.readLine();
                        }


上面果段可以轉做...

                        while ((line = in.readLine()) != null) {
                                word += line + "\n";
                        }

TOP