PrintWriter类的println()方法和wirte()方法有什么区别?
API中有
void println(String x) 
          打印 String,然后终止该行。 
 void write(String s) 
          写入字符串。 
很奇怪为什么要同时提供2个方法,测试后返现都是写入字符串,不知道有什么区别?
谁能写个简单的测试类让我seesee

解决方案 »

  1.   

    楼上说的是一个区别另外,println中调用了write,就是println会对打印的东西比write多些判断。
      

  2.   

    我个人觉得除了println换行以外没什么区别,可能是是因为write方法多于print能控制写入部分字符串:
        public static void main(String[] args) throws IOException  {
         String str = "我爱中国";
         try {
    PrintWriter pw = new PrintWriter(new File("G:\\file\\outfile.txt"));
    BufferedWriter bw = new BufferedWriter(pw);
    pw.write(str);//pw.println(str);
    bw.flush();
    pw.flush();
    bw.close();
    pw.close();
    } catch (FileNotFoundException e) {
    System.out.println("文件不存在!");
    e.printStackTrace();
    }
             }
      

  3.   

    答:区别当然大啦。write(...)的意图是按JAVA基本类型进行输出。
    如:write(12.6d)将输出double的8个字节。而print(12.6d)永远输出的是值的“字符串表示的形式”,
    即:它输出的是“12.6”这个字节串。再如:boolean a=true;write(a)输出的是一个字节。而:print(a)输出
    的"true"这个字符串。记住:print(...)永远输出的参数的字符串表示的形式。所以:若是对象o,
    则:print(o)输出的是o.toString(),而:write(o)则是对象的序列化字节流。
    以上仅供你参考
      

  4.   

    write是向一个byet[]中写值一般,而print是写一个字符串
      

  5.   

    一个简单的问题我.....怎么都不会?!再看看API去
      

  6.   

    java源代码:
    /**
         * Print a String and then terminate the line.  This method behaves as
         * though it invokes <code>{@link #print(String)}</code> and then
         * <code>{@link #println()}</code>.
         *
         * @param x  The <code>String</code> to be printed.
         */
        public void println(String x) {
    synchronized (this) {
        print(x);
        newLine();
    }
        }
      /**
         * Print a string.  If the argument is <code>null</code> then the string
         * <code>"null"</code> is printed.  Otherwise, the string's characters are
         * converted into bytes according to the platform's default character
         * encoding, and these bytes are written in exactly the manner of the
         * <code>{@link #write(int)}</code> method.
         *
         * @param      s   The <code>String</code> to be printed
         */
        public void print(String s) {
    if (s == null) {
        s = "null";
    }
    write(s);
        }