PrintStream and PrintWriter

Hi,
Could anybody tell me the difference between PrintStream and PrintWriter ?
I know that the first one operates on 8 bits streams whereas the second one
on 16 bits streams. Why could the first one not handle Unicodes properly ?
Could anybody give some explanation on that ?
The main purpose for PrintStream is to provide ability to "print representations
of various data values conveniently". So it handles all the data representations
as well as char type which is 16 bit type - so it handles Unicodes - doesn't it ?
If it does - what is the purpose for PrintWriter ?
I got confused here ...
Any links with some technical info about Stream and Writer compared
will be appreciated :)
Thanks,
Adrian

At its most basic, streams write out data and writers write out text. I searched the forum with just these terms -- printstream printwriter -- and got many useful hits. This included this gem:
http://forum.java.sun.com/thread.jspa?forumID=54&threadID=641616

Similar Messages

  • Writing to file using PrintStream and PrintWriter...

    I tried to write a string to a file, it actually ADD the string to the bottom of the text file without deleting what was already in there. at first I use PrintStream, it worked fine when run it from my MS-J++6.0, but it says "PrintStream has been deprecated by the author of java.io.printstream", and when I try to run it from IE it doesn't even work. then I look into the MSDN, it says jdk 1.1 prefer to use PrintWritier, so I change it to PrintWriter, no more error message but now the file only records the last string I entered and deleted all the text I had in there before. and it still doesn't work when I try to run it from IE. And for some reason, the program will creat the text file on my desktop(winXP) instead in the same folder where the java files are....
    Please help me understand what's wrong and how to solve it.. thank you. here is my code...
    public void storing(String msg)
              PrintWriter ps = null;
              try
                   ps = new PrintWriter(new FileOutputStream("collect.txt"), true);
                   ps.println(msg);
              catch (IOException e)
                   feedback.append("Cannot write to file.");
              finally
                   if(ps != null)
                        ps.close();

    cuz what I am doing is to have the user input 30 lines of messages, each time a message is written, they press a "next" button then that line of message will be saved to file, then the user can write the next line. I do this becuz I am affraid that the user will close the applet before he finishes all 30 line, if he does that, I still want to get as much line that the user has wrote that's why I have it write to file each time a line is written. So if I open a file at the beginning of the program, will it encounter any problem if the user close the applet without close the file??
    thanx.

  • Basic Java Help (BufferedReader and PrintWriter)

    I am studying Java for part of my degree and have become quite stuck on a question. I have set up a seperate client class and that appears to work just fine, yet when i come to set up the server class i encounter no end of problems.
    Firstly i have to set up a Server class which handles the communication to the client ;
    import java.net.*;
    import java.io.*;
    public class Server
    private ServerSocket ss;
    private Socket socket;
    //Streams for connections
    private InputStream is;
    private OutputStream os;
    //Writer and reader for communication
    private PrintWriter toClient;
    private BufferedReader fromClient;
    private GameSession game;
    //use a high numbered non-dedicated port
    static final int PORT_NUMBER = 3000;
    //set up socket communication
    public Server() throws IOException
    ss = new ServerSocket(PORT_NUMBER);
    //accept a player connection
    public void acceptPlayer()
    System.out.println("Waiting for player");
    //wait for and accept a player
    try
    while(true)
    //Loop endlessly waiting for client connections
    // Wait for a connection request
    socket = ss.accept();
    openStreams();
    //Client has connected
    game.run(); <-- this i presume runs the method run() from the GameSession Class?
    closeStreams();
    socket.close();
    catch(Exception e)
    System.out.println("Trouble with a connection "+ e);
    private void openStreams() throws IOException
    final boolean AUTO_FLUSH = true;
    is = socket.getInputStream();
    fromClient = new BufferedReader(new InputStreamReader(is));
    os = socket.getOutputStream();
    toClient = new PrintWriter(os, AUTO_FLUSH);
    System.out.println ("...Streams set up");
    private void closeStreams() throws IOException
    toClient.close();
    os.close();
    fromClient.close();
    is.close();
    System.out.println("...Streams closed down");
    // This is the top-level method to handle one game
    public void run() throws IOException
    game = new GameSession(socket);
    acceptPlayer();
    System.out.println("Server closing down");
    } // end class
    which also seems to be about what the question asks, yet i have to link this to the GameSession class sending it a reference of the socket. Which i think i have with the inclusion of the new GameSession(socket).
    When i come to write the GameSession class i realise i have to use the BufferedReader and PrintWriter when i try and do this i get a bindException as obviously the port is up and running from the Server class.
    I have tried incorporating the openStreams() in the GameSession after rermoving them from the Server class but get more Exceptions! What am i doing wron and where would i find more information on this?
    Thanks for any help you may give.

    You must redesign your Server and GameSession class.
    Study this code:
    /* save and compile as GameServer.java */
    import java.net.*;
    import java.io.*;
    public class GameServer{
      static final int PORT_NUMBER = 3000;
      private ServerSocket ss;
      GameSession game;
      public GameServer() throws IOException{
        ss = new ServerSocket(PORT_NUMBER);
        game = new GameSession();
      public void acceptPlayer(){
        System.out.println("Waiting for player");
        try{
          while(true){
            Socket s = ss.accept();
            new Thread(new ClientHandler(s)).start();
        catch(Exception e){
          System.out.println("Trouble with a connection "+ e);
      public static void main(String[] args){
        try{
          GameServer gs = new GameServer();
          gs.acceptPlayer();
        catch (Exception e){
          e.printStackTrace();
      class ClientHandler implements Runnable{
        private Socket socket;
        private PrintWriter toClient;
        private BufferedReader fromClient;
        public ClientHandler(Socket sc){
          socket = sc;
          try{
            fromClient
              = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            toClient = new PrintWriter(socket.getOutputStream(), true);
          catch (Exception e){
            e.printStackTrace();
        public void run() throws IOException{
          game.addNewClient(socket, fromClient, toClient);
    }

  • Open an objectoutputstream and printwriter on socket

    I have the following code:
    public void openConnection(String ipAddress) throws ConnectException{
    try{
          client = new Socket(ipAddress, 2000);
         out = new PrintWriter(client.getOutputStream(), true);
          objectOut = new ObjectOutputStream(client.getOutputStream());
         in = new ObjectInputStream(client.getInputStream());
         catch(ConnectException e){
         //there is no securityservice on the other side
         throw new ConnectException();}
         catch(Exception e){
                   System.out.println("Error : " +e);
    * Method that sends a list of constraints to the peer service
    * @param: SecurityConstraintList list: the list of constraints that is being sent to the peer
    * @param: String origin: the IP address of the sender, the peer uses this to save the list
    public void sendConstraints(SecurityConstraintList list, String origin){
    try{     out.println(origin);
         out.println("list");
         out.flush();
         objectOut.writeObject(list);
         objectOut.flush();
         in.close();
         objectOut.close();
         out.close();
    catch(Exception e){
         System.out.println("Error : "+e.getMessage());
         }The problem is situated in the part where I first print a line to the printwriter and after an object to the objectoutputstream. On the server i get an exception, being OptionalDataException.
    I don't get what the problem is. The exception is thrown when he reads information that he didn't expected, but i don't see how this is possible? Part of the code on the serverside is:
    else{
         if( inputLine.equals("list") ){
         //it is a securityconstraintlist that is sent
         SecurityConstraintList list;
         list = (SecurityConstraintList)inObject.readObject();
         System.out.println("Saving list");
         AppliedConstraints con = new AppliedConstraints(origin,list);
    FileOutputStream fileOutputStream = new FileOutputStream(listFile);
    ObjectOutputStream objectOut = new ObjectOutputStream(fileOutputStream);     objectOut.writeObject(con);
         objectOut.flush();                    
         objectOut.close();
         fileOutputStream.close();
         }Is it not possible to open an objectoutputstream and printwriter on the same outputstream? If so, is there an (easy) way to work around this?
    Any help would be greatly appreciated.

    Not sure what you mean by this 'reading those line
    terminators' ? Could you clarify?In your code I see a 'out.println("list");' statement. This sends the following character over your socket -- 'l', 'i', 's', 't', '\r', '\n', where the last characters denote a carriage return and a new line character respectively. Suppose the receiving en of the socket happens to be a Mac, where a line terminator is implemented as a single '\r'. This leaves the following '\n' character unread and ready to be read by the ObjectInputStream, which, obviously, doesn't know how to handle primitive data like this (hence the OptionalDataException).
    Like I wrote before -- read those individual bytes and see what really is transmitted over that socket; there must be some spurious bytes in there ...
    kind regards,
    Jos

  • How to solve the exception with socket and PrintWriter constructor

    I am working on a socket communication program and everything works fine on my computer until my boss moved my code to his computer. The following is the client code.
    The client program terminate with exception "Couldn't get I/O for the connection to local host." I have no idea how to solve the problem because there is no way out if the two statements (socket constructor and PrintWriter) fail.
    /*the program shall close connections and exit if the user clicks 'e'.*/
    public class LocalClient extends JPanel implements KeyListener {
    Socket localSocket = null;
    PrintWriter out = null;
    BufferedReader in = null;
    char fromServer = ' ';
    public LocalClient() {
    try {
    localSocket = new Socket("a029243.cs.uregina.ca", 4444);
    out = new PrintWriter(localSocket.getOutputStream(), true);
    } catch (UnknownHostException e) {
    System.err.println("Don't know about local host.");
    System.exit(1);
    } catch (IOException e) {
    System.err.println("Couldn't get I/O for the connection to
    local host.");
    System.exit(1);
    addKeyListener(this);
    }//end of constructor
    /*the component needs to be focused in order to respond to user input */
    public boolean isFocusTraversable() {return true;}
    public void keyPressed(KeyEvent evt) {
    public void keyReleased (KeyEvent evt) {
    public void keyTyped(KeyEvent evt) {
    System.out.println("key typed is called ");
    char fromClient=evt.getKeyChar();
    if (fromClient!= ' ') {
    if (fromClient=='e')
    try {
    out.close();
    localSocket.close();
    System.exit(1);
    } catch (IOException e)
    {System.out.println("connection closed");}
    else {
    System.out.println("Client: " +
    fromClient);
    out.println(fromClient);
    out.flush();}
    public static void main(String[] args) throws IOException {
    JFrame frame1=new JFrame();
    Container contentPane=frame1.getContentPane();
    LocalClient lc = new LocalClient();
    contentPane.add(lc);
    frame1.pack();
    frame1.setSize(50,50);
    frame1.setVisible(true);
    }//end of main
    } //end of class

    Add e.printStackTrace() or System.out.println(e) to the catch block of the IOException. The IOException has a message about what went wrong.

  • NullPointerException Using PrintStream or PrintWriter

    Here is the code that I am using. I am taking the output of a program and trying to write that output to a file. When outputting to the file I receive a null pointer exception that I don't know why I am getting. I am using PrintStream here but I also tried using PrintWriter and I got the same error. If I uncomment the System.out.println statement the first line is printed to the console window, but then when it tries to print that line to the file I apparently get the NullPointerException. Can anyone help? Thank you. Here is that bit of code.
    p = r.exec(myprogram);
                                  InputStream in = p.getInputStream();
                                  BufferedReader br = new BufferedReader(new InputStreamReader(in));
                                  String line = null;
                                  try
                                       PrintStream outFile = new PrintStream(new FileOutputStream("testresults.txt"));
                                  catch(FileNotFoundException fe)
                                       System.out.println("File not found: " + fe);
                                  while ((line = br.readLine()) != null)
                                       //System.out.println(line);
                                       outFile.println(line);
                                  p.waitFor();

    I can tell you exactly why... Here's an example
    public static void aMethod() {
      String s = "Foo";
        String s = "Bar";
      System.out.println(s);
    }The value output is "Foo" because the 's' declared in the parenthesis is a different variable in it's own scope.
    Your code does something similar when you did the following
    try {
      PrintStream outFile = new PrintStream(new FileOutputStream("testresults.txt"));
    } catch(FileNotFoundException fe) {
      System.out.println("File not found: " + fe);
    }This declares a variable in the scope of the try block and assigns a reference to a new PrintStream object. However this variable ceases to exist immediately following the closing parenthesis of the catch block.
    Since your code compiles you must, further up have already declared outFile so I would change the code to
    try {
      outFile = new PrintStream(new FileOutputStream("testresults.txt"));
    } catch(FileNotFoundException fe) {
      System.out.println("File not found: " + fe);
      outfile = null;
    }Note that this means if the exception occurs, outFile will be null. You need to decide what action to take in this situation.
    Hope that helps - now put up your Dukes... ;)

  • Difference between System.out.println(..)and PrintWriter.println(..)

    Hello every one
    With System.out.println(..) we can print to Console.
    But System.out internally creates PrintWriter object.So why cant we use
    PrintWriter.println(..) directly to write to console.
    Is there aany disadvvantage with PrintWriter.println(..).
    If so can anyone please tell me what is that and
    what is the advantage we r going to get with System.out.println(..) method of writing to console.

    kirn291 wrote:
    With System.out.println(..) we can print to Console.If you want to be very precise, then you have to say that System.out.println() writes to the default output stream. This is usually shown at the console, but can equally well go into a file (if you've redirected it) or nowhere (when running without a console).
    But System.out internally creates PrintWriter object.Not exactly. It refers to a PrintStream object.
    So why cant we use
    PrintWriter.println(..) directly to write to console.Because if you create a PrintWriter it is just another PrintWriter that writes to whatever you specified at the constructor. It is not the same thing as the one PrintStream that is used in System.out.
    what is the advantage we r going to get with System.out.println(..) method of writing to console.The advantage is that it's the only way to do it. Could you post an example of how you'd think of a different way to write to the console?

  • OutputStream and Printwriter

    Is it possible within the same servlet to do both of these commands.
    I need to use the response to firstly get an OutputStream.
    (This is needed to draw out a dynamic graph)
    so use the following code.
    OutputStream out2 = response.getOutputStream();
    ChartUtilities.writeChartAsJPEG(out2, chart, 600, 300); But then i also need to get a PrintWriter.
    so use the following code.
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();I use this because the servlet already existed before inclusion of the chart.
    Is there any way to include both these commands within the same servlet ie within the doget method??
    I have tried this but it either just prints out the graph and doesnt do hte chart or doesnt do hte chart and prints out the servlet html code.
    Any advice gracefully accepted.
    delboy

    Nope. Not possible with one request.
    You will need to make two requests to your servlet. One for the image, the other for the accompanying text.
    I would suggest you send back the html text first, including a link to load the image into the page (via the servlet call)
    good luck,
    evnafets

  • OutputSteam and PrintWriter

    I'm having some trouble understanding streams.
    What is the difference between and OutputStream object and a PrintWriter object?
    I can use both to write to a client by using outputStream.println() or printWriter.println(), so what do they do differently?
    Thank you
    _

    Hi theyuv,
    PrintWriter is designed to work only with text-output streams, the streams used to build only text formatted files (.txt, .html, .xml, .ini, .csv, ...).
    OutputStream is designed to work with all kind of streams, binary-output streams and text-output streams; with an OutputStream, it's possible to build files in whatever format you want (.jpg, .wav, .txt, ...).
    See Tutorial Lesson: [*Basic I/O*|http://java.sun.com/docs/books/tutorial/essential/io/]

  • ExecutorService using bufferwriter and printwriter

    I'm trying to create a simple multithread chat server for class. when i run the server and connet with multiple clients the server only outputs to one client. it also appears that the server will keep a running list of who sent data to the server, but will only repot back to the last connected client.
    I need help
    the java code is located at the attached link.
    [http://www.ralieghnet.com/?q=node/23]

    *** chatServer ***
    import java.net.*;
    import java.io.*;
    import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    public class chatserver {
          private final static int maxClients = 10;
    public static void main(String[] args){
            ServerSocket sock = null;
            Socket client = null;
            ExecutorService threadExecutor = Executors.newFixedThreadPool(maxClients);
            chatServerConnections chatConnection = new chatServerConnections();
            try{
                sock = new ServerSocket(6013);
                System.out.println("Now accepting Connections");
                while(true)
                    chatConnection.chatConnections(sock.accept());
                    chatServerListener chatListen = new chatServerListener(chatConnection);
             threadExecutor.execute((Runnable) chatListen);
            catch (IOException ioe){
                System.err.println(ioe);
    }*** chatServerConnection ***
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.PrintWriter;
    import java.net.InetAddress;
    import java.net.Socket;
    public class chatServerConnections
    private Socket clientSocket;
    private BufferedReader input;
    private PrintWriter output;
            chatServerConnections()
               clientSocket = null;
               input = null;
               output = null;          
    public void chatConnections(Socket socket)
                clientSocket = socket;
                System.out.println(clientSocket);
                try{
                    input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                    output = new PrintWriter(socket.getOutputStream());
                catch (IOException ioe)
                    System.err.println(ioe);
    public String getInput() throws IOException
                String temp;
                temp = input.readLine();
                input.reset();
                return temp;
    public void setOutput(String inString)
                output.println(inString);
                output.flush();
            public String getAddress()
                return " connected @ " + clientSocket.getLocalAddress() +" " +clientSocket.getLocalPort() +" >>";
    }*** chatServerListener ***
    import java.net.Socket;
    import java.io.*;
    class chatServerListener implements Runnable{
        private String userName = null, userInput = "";
        private chatServerFile csf;
        private chatServerConnections chatConnect;
        public chatServerListener(chatServerConnections connect) throws IOException
            chatConnect =  connect;
            csf = new chatServerFile();
        chatServerListener() {
            throw new UnsupportedOperationException("Not yet implemented");
        public void run()
            try
                if(userName == null)
                    userName = chatConnect.getInput();
                    //userName = input.readLine();
                    chatConnect.setOutput("<< User: " + userName + " connected.>>");
                    //output.println("<< User: " + userName + " connected.>>");
                    System.out.println("<< User " + userName + chatConnect.getAddress());
                    csf.addData("<< User " + userName + chatConnect.getAddress());
            catch (IOException ioe)
                System.err.println(ioe);
            try{
                while(!(userInput == null))
                    userInput = chatConnect.getInput();
                    try
                    if(!(userInput.equalsIgnoreCase("")))
                         if(userInput.equalsIgnoreCase("GetHistory"))
                          try{
                           userInput = csf.getData();
                                 if(userInput == null)
                                  userInput = "<< SERVER: Could not complete the requested action >>";
                          catch (IOException ioe)
                           System.err.println(ioe);
                         else if(userInput.equalsIgnoreCase("quit"))
                          try{
                           chatConnect.setOutput("<< Good By >>");
                              csf.addData("<< User: " +userName + " Disconnected >>");
                              //clientSocket.close();
                              break;
                          catch (IOException ioe)
                           System.err.println(ioe);
                         csf.addData("\n" +userName + ": " + userInput);
                            chatConnect.setOutput(userName +": " +userInput);
                            if(userInput != null)
                             System.out.println(userName +": " +userInput);               
                    catch (NullPointerException npe)
                     System.err.println(npe);
                     csf.closeFile();
                System.out.println("<< User: " +userName + " Disconnected >>");
                csf.closeFile();
            catch (IOException ioe)
                System.err.println(ioe);
                System.out.println("<< User: " +userName + " Disconnected >>");
                csf.closeFile();

  • PrintStream and BufferedOutputStream

    I am using a text file as a log file for a program I am working on. I would like to use PrintStream. Does it pay to use a BufferedOutputStream with a PrintStream or will PrintStream be sufficiently buffered? I was thinking of using either:
    PrintStream logger = new PrintStream( new BufferedOutputStream( new FileOutputStream( "file.log" ) ) );or
    PrintStream logger = new PrintStream( new FileOutputStream( "file.log" ) );Can anyone tell me for sure if there is a big difference between either method and which would be more appropriate?

    Why not just try it - write a program with a start/end timer, output 10,000 lines.

  • Why using BefferedReder and PrintWriter if we have Input/OutputStream

    hi
    i've been wondering if we have an InputStream and OutputStream why using PrintWriter and BufferedReader
                    in=s.getInputStream();
                    out=s.getOutputStream();
                    bfr=new BufferedReader(new InputStreamReader(in));
                    writer=new PrintWriter(out,true);where s ia a socket
    Edited by: scrolldown on Mar 29, 2008 3:03 AM
    Edited by: scrolldown on Mar 29, 2008 3:04 AM

    Everything that is a InputStream/OutputStream is used to handle raw byte streams.
    Everything that is a Reader/Writer is used to handle character data.
    In your case the InputStreamReader provides the conversion from raw bytes to character data. Usually it does so using some specified encoding, in your case it uses your platform default encoding.
    The PrintWriter does the same for the output, but doesn't allow you to specify an encoding (for this you'd have to use an OutputStreamWriter).
    And please note, that it's usually an error to do any byte -> character or character -> byte conversion without specifying a character set, especially when handling sockets, because then the platform default encoding will be used which can be different from computer to computer and thus you don't know what exactly is sent over the wire.
    If you don't know what I'm talking about, then read [The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)|http://www.joelonsoftware.com/articles/Unicode.html], an excellent article that gives a good overview over the matter.

  • Formatting output to a text file (using FileWriter and PrintWriter)

    Hi Folks
    I am using the bit of code below to save output from a gui to a text file. The data is entered line by line in the form eg,
    "one two three four"
    "five six seven eight"
    I am also reloading this data back in to a TextArea in the GUI for viewing if required. The annoying thing that upon reloading, the data appears in one long line. The TextArea does not offer a line wrapping facilty (well I don't know how to impement it, it exist). Consequently, I would be quite grateful if somone could come come to my assistance. Any of these would graciously appreciated:
    1. Forcing the TextArea to word wrap
    2. Manually inserting some type of newline character at the end of the outbound
    text
    3. Or any other procedure you experts can dream up :-)
    Cheers
    public void actionPerformed(ActionEvent e) {
    if (e.getSource() == loadButton) {
    getFileDialog = new FileDialog(this,
    "Select or enter the name of the file you wish to write to.",
    FileDialog.LOAD);
    getFileDialog.setDirectory("C:\\Work\\java_tutorials");
    getFileDialog.show();
    fileName = getFileDialog.getFile();
    if(fileName == null) {
    return;
    directory = getNameBox.getDirectory();
    path = directory + fileName;
    fileConfirmation.setText(path);
    if (e.getSource() == saveButton ) {
    try{
    outputFile = new PrintWriter( new FileWriter(fileName, true), true);
    outputFile.print(inputTextArea.getText() );
    outputFile.close();
    catch (FileNotFoundException e1) {
    return;
    catch (NullPointerException e2) {
    return;
    catch (IOException e3) {     
    JOptionPane.showMessageDialog(null,
    "There was an error in opening this file!");
    System.exit(0);
    }

    'you can use "append()" method...
    ex.
    // some code here...
         inputTxtArea.append(data+"\n");  //<<-- you need to put '\n'
    // some code here...

  • Copying Formatted Data

    Are there any methods that can read a text file that contains tabs, carriage returns, etc. Then writes it out identically to an output file? I need something that can copy the exact formatting doing read and then write.

    Thanks. Looking around I found PrintStream and PrintWriter. Would these work by any chance?

  • File Chooser and Scanner/ PrintWriter

    I'm trying to use the file chooser and scanner and printwriter together. How can I go about this?

    import java.io.*;
    import java.util.Scanner;
    import javax.swing.JFileChooser;
    * @author Originative
    public class Test {
        JFileChooser jf=new JFileChooser(".");
        String fileName="";
        public static void main(String [] nix){
            Test t=new Test();
            t.Actor();
        public void Actor(){
            try{
                Scanner c=new Scanner(System.in);
                System.out.print("Enter 1 to Open JFileChooser : ");
                int k=c.nextInt();
                if(k==1){
                    int val=jf.showOpenDialog(jf);
                    if(val==JFileChooser.APPROVE_OPTION){
                        File fi=jf.getSelectedFile();
                        fileName=jf.getSelectedFile().toString();
                        PrintWriter pw = new PrintWriter(System.out, true);
                        pw.println(fileName);
                if(k!=1){
                    System.out.println("Bye Bye  :)");
            catch(Exception d){
                System.out.println(d);
    }A sample you can use in this way and many many many many others :)

Maybe you are looking for