Skip to content

PrintWriter

Solves problems of FileWriter and BufferedWriter

Constructors :

  1. PrintWriter bw = new PrintWriter(String fname);
  2. PrintWriter bw = new PrintWriter(File f);
  3. PrintWriter bw = new PrintWriter(Writer w);

Methods

  1. write (int ch)
  2. write(char[] ch)
  3. write(String s)
  4. flush()
  5. close()
  6. print(char ch)...print(int i)...print(boolean b)...print(String s)
  7. println(char ch)...println(int i)...println(boolean b)...println(String s)

Examples

Write On File

  • Write some text on file named "abc.txt".
    import java.io.*;
    
    class Sample {
        public static void main(String[] args) {
            try {
                PrintWriter pw = new PrintWriter("abc.txt");
                pw.print('d'); // Writes character
                pw.print(100 + "\n"); // Writes integer
                pw.print(true + "\n"); // Writes boolean
                pw.print('c' + "\n"); // Writes Character
                pw.print("gces" + "\n"); // Writes string
                pw.flush();
                pw.close();
            } catch (IOException error) {
                error.printStackTrace();
            }
        }
    }