FileOutputStream

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package filetestread;



import java.io.*;
/**
 *
 * @author Administrator
 */
public class Main {


    public static void main(String[] args) throws IOException{
     

      FileInputStream in = null;
        FileOutputStream out = null;
        try {
            
            out = new FileOutputStream("myfile1.txt");
            int c;

            while ((c = in.read()) != -1) {
                out.write(c);
            }

        } finally {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
        }
    }

}

I have a text file I want read it and show the content by byte stream

But I get this error:

run:
Exception in thread “main” java.lang.NullPointerException
at filetestread.Main.main(Main.java:28)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)

Did you initialize the variable “in”?

public class Main {


    public static void main(String[] args) throws IOException{
     

        FileInputStream in = null;
        //FileOutputStream out = null;
        try {
            
            in = new FileInputStream("myfile1.txt");
            int c;

            while ((c = in.read()) != -1) {
                System.out.print(c);
               // out.write(c);
            }

        } finally {
            if (in != null) {
                in.close();
            }
           // if (out != null) {
               // out.close();
            }
        }
   // }

}

Output:

1039710310011510310011510311597100103100115103100115103100115103100115103100115103100115103

Now, I want to see the contents as the character by using Byte stream, How can I do this?

Hi abalfazl,

Could you explain more about the “Byte stream”?
If want to display the contents of a simple text file to the console or stdout, you could use a

  1. FileReader instead of the FileInputStream
  2. and wrap the FileReader in a BufferredReader and use that to read Strings line by line.

Jurn

javadoc:
A FileInputStream obtains input bytes from a file in a file system. What files are available depends on the host environment.
FileInputStream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader.

http://download.oracle.com/javase/tutorial/essential/io/bytestreams.html

I don’t know if FileInputStream is not suitable for read character, Why does it used to copy a text file in Sun example?

I don’t know why it would be used as an example. It will work, as a text file is a byte stream. But the Reader is more appropriate to use and AFAIK will save you from having to deal with some potential problems

[code=java]package filetestread;

import java.io.*;
/**
*

  • @author Administrator
    */
    public class Main {

    public static void main(String args) throws IOException{

     FileInputStream in = null;
     //FileOutputStream out = null;
     try {
         
         in = new FileInputStream("myfile1.txt");
         int c;
    
         while ((c = in.read()) != -1) {
             System.out.print(c+ " ");
            // out.write(c);
         }
    
     } finally {
         if (in != null) {
             in.close();
         }
        // if (out != null) {
            // out.close();
         }
     }
    

    // }

}



When I run this program the result is:

84 104 105 115 32 105 116 32 121 111 117 114 32 115 111 110 103

T>84
h>104

The sentence in file is :

This is your song

When I check ascii table, These numbers match with that table:

http://www.asciitable.com/


Now my question is

How a character save in 2 bytes in JAVA? 

For example, "T". 

The ascii code for a is 84. 
http://www.asciitable.com/ 

How this number, 84 saves in two bytes?

If I use cast, I can see character in output:

System.out.print((char)c+ " ");

Is there a way in JAVA that I can see character in output without using cast?

It depends on what encoding your file is using. Your simple text file looks like ASCII, and is only taking up 1 byte per character.
1 byte is 8 bits, which could be one of 256 values.

Other character encodings can take more than 1 byte per character. e.g. UTF-8

hope this helps…

Jurn

[code=java]public class Main {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) throws IOException{

  
    

    try {
        BufferedReader i = new BufferedReader(new InputStreamReader
                          (new FileInputStream("myfile1.txt"),"UTF-8"));
    String str1 = i.readLine();

  System.out.println("File text : "+ str1);
    System.out.println("Reading Process Completly Successfully.");
        }
    

catch(UnsupportedEncodingException ue){

   System.out.println("Not supported : ");

}

 catch(IOException e){

   System.out.println(e.getMessage());

   }
}

}



This is the text in the file, I use netbeans IDE

abalfazl 

ابالفضل 


but the output is:


> File text : ?abalfazl 
Reading Process Completly Successfully.


How can I fix it?

I’d check 2 things…

first verify that myfile1.txt is really saved with UTF-8 encoding.

you can use the unix (or cygwin) ‘file’ command
or on windows use Ultraedit - it tells you the file encoding.
otherwise, zip it, and upload it here and someone could help verify.

another problem could simply be that your console or font in netbeans doesn’t support utf-8. I’m not familiar with netbeans, someone else could probably help you there.

Jurn

I think that this code be helpful:

System.out.println(System.getProperty("file.encoding")); 
System.out.println(Charset.defaultCharset().name());