Using file input stream

hello,
i have the following problem.I have a file which consists of characters. I have to consider each character at a time for further manipulation, so in order to that i need to store it in an array..i have read the file using the following ..
public class fileinput
public static void main(String args[]) throws IOException
int size;
InputStream f = new FileInputStream("laser.txt");
System.out.println("total available bytes:" +(size=f.available()));
Now is it possible to store this file into a array ..when i use the following i'm getting an error coz "f.read()" returns an integer so it is incomaptible....
byte b[]=new byte[size];
for(int i=1;i<=size;i++)
b=f.read();
somebody plz help...

1. It is really inefficient to read 1 byte at a time. You might do better to read all the bytes you can get and then see what's in the byte[]
2. When using read(), here's what you want
int b;
while ( b = in.read() != -1) {
byte bb = (byte) b;

Similar Messages

  • How to get file input stream from the client machine by JSF Fileupload API?

    Dear Friends,
    How to get the file input stream from the client machine by JSF HtmlFileupload or fileupload API. At present, if i execute the file upload code in the client machine, it is able to get the local path of the file and looking for the file in server machine. So i am getting FileNotFoundException.
    E.g., If a file is located at client machine at following location means "C:\Test\Test.txt",
    uploadClass.getFileuploadComponent().getFilename().toString() returns "C:\Test\Test.txt". But it is looking for that file in server and throwing FileNotFoundException.
    Please post your replies soon.
    Thanks,
    JP

    Depends on which version of JSF you're using. If JSF 1.2, I wouldn't even bother trying to hack this into JSF itself unless you can use something like Seam 2 or richfaces.
    http://docs.jboss.org/richfaces/latest_3_3_X/en/devguide/html/rich_fileUpload.html
    http://docs.jboss.org/seam/2.2.1.CR3/reference/en-US/html/controls.html#d0e29259 (look for s:fileUpload)
    But if I were you, a simple non-jsf form with a servlet works best for taking file uploads.
    As for JSF 2.0, there are other ways of getting it done.
    http://balusc.blogspot.com/2009/12/uploading-files-with-jsf-20-and-servlet.html

  • Re: File Input Streams FileNotFoundException

    Hi,
    I'm having problems with file input streams.
    The program is supposed to read from an external file but when I run it in Sun ONE Studio 4 (update 1), it gives me a FileNotFoundException (The system cannot find the file specified). The file, class.dat, is in the same folder as the .java and .class files.
    Anyway, so I run the program through MS-Prompt commands and there is no problem. It executes fine and gives the right output. Go figure.
    Can anyone shed some light on what is going on? Anyone else with the same problem? Is there something I need to configure in SunStudio? Please help...
    Thanks
    The code is taken directly from Sams Java in 21 days.
    // code
    import java.io.*;
    public class ReadBytes {
    public static void main(String[] arguments) {
    try {
    FileInputStream file = new
    FileInputStream("class.dat");
    boolean eof = false;
    int count = 0;
    while (!eof) {
    int input = file.read();
    System.out.print(input + " ");
    if (input == -1)
    eof = true;
    else
    count++;
    file.close();
    System.out.println("\nBytes read: " + count);
    } catch (IOException e) {
    System.out.println("Error -- " + e.toString());

    FileInputStream file = new FileInputStream("class.dat");Is this the line that is giving you the error message? Always, when trying to open a disk file, give the full path. This is because, FileNotFoundException is thrown only in cases when your file cannot be found by your program. But you say that the file exists.
    Try giving your full path for the file...like:
    FileInputStream file = new FileInputStream("C:/Program Files/class.dat");
    //Ofcourse your path will be different. This is just an example!So try giving the full path and let me know.
    Vijay :-)

  • File Input Stream problem

    i have a text file that i want to read to be my input into my database in db4o. i was looking through the websites. like http://java.sun.com/javase/6/docs/api/java/io/FileInputStream.html
    and
    http://www.java2s.com/Code/JavaAPI/java.io/FileInputStreamavailable.htm
    there were different types too. like FileReader, FileInputStream. can anyone explain to me the differences between this two?
    below is an example on how inside my text file is going to look like
    Jack | China | 23
    Helen | Holland | 34
    Jenny | US | 34
    Micheal | Brazil | 23
    different attributes is separated by "|". i need to capture all this from a text file and store it in my db4o database. maybe someone could guide me on this? i am very new in java so forgive me if i am wrong. Thanks alot

    ok. thanks alot. i will look into it
    the "|" is because i want to separate different
    attributes by using symbol
    for example:
    Name | Address | Age
    Alex | Australia | 34
    Jack | Malaysia | 32
    Kate | Africa | 11
    Holmes | California | 54
    from there, this will be captured by the
    BufferedReader (because this is use to capture text)
    and read it and then stored inside the db4o. the
    problem now is how can i capture the data and
    automatic separate it as different field with this
    "|" symbol
    Message was edited by:
    erickhHow about using Scanner:
    Scanner inFile = new Scanner(new FileReader("a:\\file.txt"));

  • Does File Input stream encode data

    Hi,
    When I retrieve a binary stream of an image from a database and print out all the bytes and then retrieve data with a FileInputStream from the same image stored as a file, and print the results, the 2 printouts are completely different. Can anyone explain why?
    Thanz

    However, the InputStreams do treat bytes as signed entities (-128 to +127 rather then 0 to 255). If you just print these out then you will get odd results which do not match the data you are expecting.
    If you do the following
    int tmp = b & 0xFF;
    where b is a byte from your input then tmp will contain the unsigned value of that byte rather then the signed value.
    matfud

  • File Input Stream

    Hello !
    The FileInputStream has a constructor which uses FileDescriptor object as "FileInputStream(FileDescriptor fdobj)"
    The practical use of FileDescriptor object is the FileInputStream and FileOutputStream to contain it.
    Can someone help me how to make an elaborate use of it ? I want to use it in some manner in the following program .
    God bless you.
    NADEEM.
    import java.io.* ;
    public class CopyingText {
    public static void main(String args[])  { 
    Thread t = new Thread();
      try {
       System.out.println("Enter java CopyingText Source.txt Target.txt");
       FileInputStream  a = new FileInputStream(args[0]);
       FileOutputStream b = new FileOutputStream(args[1],true);        
       System.out.println("Source size: " + a.available());
       System.out.println(a.getFD());
        CopyingTxt rw  = new CopyingTxt(a,b);
        rw.fileCopying();
    //    rw.bytesAvailable();             Giving IOException: Bad file descriptor : Reason ?
      } catch(Exception e) {
        System.out.println("Exception : main() :" + e );
        t.dumpStack();
    class CopyingTxt   {
      private int i  , j  ;
      FileInputStream  fa ;
      FileOutputStream fb ;
      CopyingTxt(FileInputStream a, FileOutputStream b) {
       fa = a ;
       fb = b ;
      public int bytesAvailable() throws IOException {
       System.out.println(fa.getFD());
       System.out.println(fa.available());
        return fa.available() ;
      public void fileCopying() throws IOException {
       do {
        i = fa.read();
        j++ ;                                  
        if(i != -1) fb.write(i) ;
       } while(i != -1);                       //EOF condition  -1 .
       System.out.println("Bytes read : " + (j-1) + " / " + fa.available());
       bytesAvailable();
       fa.close();
    //    fa.finalize();
       fb.close();
    //    fb.finalize();
    }

    Please don't crosspost. It cuts down on the effectiveness of responses, leads to people wasting their time answering what others have already answered, makes for difficult discussion, and is generally just annoying and bad form.

  • I have a problem in using input stream in ftp

    Hi dear members,
    i have a problem. i am using below code to have inputstream of the file. f is directory and osconfigscript[q] is a file, which is already existing.
    InputStream is = new BufferedInputStream(new FileInputStream(new File(f,osconfigscript[q])));
    Later on i am using this input stream to ftp it .
    ftp.setFileType(FTP.BINARY_FILE_TYPE
    ftp.storeFile(osconfigscript[q],is) ;
    But the content i am getting in the ftp server is not same as i have sent.
    though the file name and it's remain same. the content become unreadable. the ftp class that i have used is
    "org.apache.commons.net.ftp.FTPClient".
    what should i do to make my content readable in the ftp server.

    I found the answer myself. Actually i was doing hot deployment in my jboss server (through eclipse jboss plug-in) . This was cause of the error .i have done the cold deployment now it is working.
    Hot deployment is works better in the JDeveloper then in eclipse - jBoss combo.
    no i have not used inputstream stream between its creation and passing it into the ftp method.

  • URLConnections and Input Streams

    I am trying to get a jar file I have up on a web server.
    First I make a connection to the server requesting the file..that works fine.
    Second i want to use an input stream to bring in the file so i can read its contents.
    The problem lies in using the InputStream to read a URL connection.
    I have tried using the JarInputStream but that wont work.
    Do I need to take my URLConnection and convert it to an object or data type that I am not aware of?
    URL url = new URL("http://www.domain.com/myfile.jar");
    URLConnection conn = url.openConnection();
    JarFile in = new JarFile(new BufferedReader(new InputStreamReader(conn)));
    Any ideas fellas?

    At this point that is all I want to do. Just download the file.
    Thats where I am having trouble.
    Once I get it downloaded it should be fine.
    Should I maybe write the input of the file coming off the server to input of a new file?

  • What's the fastest input stream reader?

    Here's my candidate for the fastest stream reader. My interest and testing is with file input streams, but it's nice to support any stream.
         public static String readStream(InputStream is) throws IOException{
              int i, length = 0;
              StringBuffer s = null;
              char[] c = null;
              InputStreamReader isr = new InputStreamReader(is);
              while(length != -1){
                   length = is.available();
                   if(c == null) c = new char[length];
                   isr.read(c, 0 , length);
                   i = isr.read();
                   if(i == -1){
                        if(s == null) return String.copyValueOf(c);
                        else break;
                   }else{
                        if(s == null) s = new StringBuffer();
                        s.append(c, 0, length);
                        s.append((char)i);
              return s.toString();
         }

    I do have a separate function that's optimized for file reading. I have tried the simpler implementation, and it is slower.
    The reason I'm reading into a StringBuffer is that I have a DOM framework that allows you to load an xhtml document, do stuff, and then print out the result. I have Styles which allow you to merging a document with a style document and then in your project specific code, modify the resulting document. In one case, my style document is located on a remote machine and has the following:
    <link rel="stylesheet" href="<!--SOURCEURL-->style.css" type="text/css" media="all"/>
    I allow the Style class to override a "replaces" function that does string replacements and thus allows the non-xml compliant comment to be replaced by the appropriate URL prefix for the remote machine. I admit this probably isn't the best way to do it, since the comment makes the document invalid. I'd like to change to a better way, but I'd still like to keep the option of doing textual replaces on the input document before loading it into DOM. This may be a requirement since it is the convension that was previously used before we started using DOM.
    As for bounded size, I figure the StringBuffer is going to be a lot smaller than the DOM representation anyway. And, neither should be that significantly large.

  • Reading an image from input stream

    Hello all,
    I'm familiar with setting up an input stream but I have never actually done it. I'm making a connection to a URL (a JPG image). I would like to read the JPG from the URL using an input stream. With the URL class I was able to open a stream, however, I'm not exactly sure how to read from it.
    I'm aware of the read() method and read(byte[]) methods of inputstream. But how do I actually implement it?
    If I use read(), then bytes come in individually... do I need to combine them at one point? If I read the bytes into an array, how do I determine what size to set the array and how do I convert the byte array into an Image or ImageIcon?
    Please advise.
    R. Alcazar

    Hi,
    See http://java.sun.com/products/jdk/1.2/docs/guide/2d/api-jpeg/
    and especially JPEGCodec.createJPEGDecoder(java.io.InputStream).
    Anyway, you might not want to do it with InputStream. Instead you could try something like this:
    URLConnection con = // get it somehow
    Image i = (Image) con.getContent(new Class[] {Image.class});
    However, If you still want to use the InputStream, here you go with some pseudo code:
    InputStream in = // get the input stream with JPEG data...
    JPEGImageDecoder dec = JPEGCodec.createJPEGDecoder(in);
    Image i = dec.decodeAsBufferedImage();
    You can get the InputStream from the URLConnection with getInputStream(). However, I don't remember if the InputStream contained also the HTTP (or what ever protocol the URL specifies) headers. If it contains the headers, then you must rip them of before giving the InputStream to the JPEGCodec...
    If this is the case, try calling the URLConnection.getHeaderFields() method before getInputStream. This might not work though.

  • File input question

    I'm new to java and I'm trying to write a program using file input/output.
    The user is asked for the names of an input file and an output file.
    My question is that in case I don't specify the path of the input file, where should it reside?
    thanks,

    My question is that in case I don't specify the path
    of the input file, where should it reside? In the present working directory. Which is not reliably known at runtime. If the input file will remain unchanged, you can put it into your JAR (if you create one) or somewhere else in your classpath, like the package root, and use getClass().getResourceAsStream("/thefile.ext") to load it. That will always work.

  • How do I return an input stream from a text file

    Suppose there's a class with methods..
    one of the methods is something like..
    public int value() and has a return statement at the end obviously for returning an int value..
    Another method reads a text file and creates an input stream..
    Scanner data  = new Scanner(new File(input.next()));
    I want to return the data when I do a call to this method, but I'm not sure what the method heading would look like..

    flounder wrote:
    Are we supposed to magically know what those errors are? Do you think that copying and pasting the exact error messages and indicating the lines they occur on would be useful to us?Sorry about that..
    I've replicated the same code below; and put the number of the line where the error is.
    +cannot find symbol variable read     [line 21]+
    +cannot find symbol variable read     [line 23]+
    +cannot find symbol variable read     [line 29]+
    +cannot find symbol variable read     [line 31]+
    +cannot find symbol variable inputStream     [line 44]+
    +calculate() in textInput cannot be applied to (java.util.Scanner)     [line 57]+
    the reason I have the _______ for the createInputStream() method is because I'm not really sure what the heading type should be to return the input stream.
    import java.io.*;
    import java.util.*;
    public class textInput
              public void requestFileName()
                   Scanner input = new Scanner(System.in);
                   System.out.print("Enter file name: ");
              public _______ createInputStream() throws FileNotFoundException
                   Scanner input = new Scanner(System.in);
                   Scanner read = new Scanner(new File(input.next()));
                   return read;
              public void calculate() throws IOException
    21           double max;
                   double min;
    23            int count = 0;
                   double total = 0;
                   if (read.hasNextDouble())
                        double temp = read.nextDouble();
    29                 max = temp;
                        min = temp;
    31                 count++
                        total += temp;
                        while (read.hasNextDouble())
                             double current = read.nextDouble();
                             count++;
                             min = Math.min(current, min);
                             max = Math.max(current, max);
                             total += current;
                   System.out.println("Max of: " + max);
                   System.out.println("Min of: " + min);
    44            System.out.println("Average of " + total/count);
              public void close() throws IOException
                   inputStream.close();
              public static void main(String[] args)
                   textInput run = new textInput();
                   try
    57                 run.requestFileName();
                        run.createInputStream();
                        run.calculate();
                        run.close();
                   catch(FileNotFoundException e)
                        System.out.println("File not found.");
                        System.exit(0);
                   catch(IOException e)
                        System.out.prinln("File not found.");
                        System.exit(0);
    }

  • Parse XML input stream (no .xml file)?

    i have a java applet calling a web service that returns XML data as an input stream (char by char from SOAP) to this applet. if i append a all the chars to a string, is there some XML tool that will parse the string as if it were an XML document (like a getElement functions)?
    the applet cannot write the data to a .xml file, and i don't want to mess around with .jarsigning. any ideas?
    thanks,
    jonathan

    The XML parsers you are likely to be using support receiving input from a variety of sources besides files. For example you could parse XML from a String variable by passing a StringReader wrapping that String to the parser. Check the documentation for more details.

  • How to read a file as an input stream after it's posted in an HTML form ?

    Hello,
    I want to read client file after it's posted in an HTML form. But, I don't want to upload it to filesystem or database. I want to read posted file as an input stream. How can I do that ?
    thanks in advance...

    A couple of things. If you have a FILE field in your form, the enctype of the form must be multipart/form-data. Check this link
    http://www.htmlhelp.com/reference/html40/forms/form.html
    Also, when a file is uploaded you cannot use the regular methods to get at the name/value pairs or the file itself. You'll have to use a utility like MultiPartRequest or write your own based on the RFC for Multipart requests.
    http://www.servlets.com/cos/javadoc/com/oreilly/servlet/MultipartRequest.html
    You will need some temporary file system to store this and then delete it when you are done with it.
    hth

  • Oracle Blob using Java help (Error: JVM_recv in socket input stream read )

    I am trying to insert a record with Blob column (size of image 'mg.jpg' about 15KB) and I get the runtime error:
    [java] java.sql.SQLException: Io exception: Connection reset by peer: JVM_recv in socket input stream read
    [java]      at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:134)
    [java]      at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:179)
    [java]      at oracle.jdbc.dbaccess.DBError.throwSqlException(DBError.java:333)
    [java]      at oracle.jdbc.driver.OracleStatement.executeNonQuery(OracleStatement.java:2061)
    [java]      at oracle.jdbc.driver.OracleStatement.doExecuteOther(OracleStatement.java:1940)
    [java]      at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:2709)
    [java]      at oracle.jdbc.driver.OraclePreparedStatement.executeUpdate(OraclePreparedStatement.java:589)
    [java]      at test.ProvisioningParser.TestBlob.main(Unknown Source)
    This is what code looks like: I am not sure what's wrong, any help appreciated. Thanks!
         try{
                   Class.forName("oracle.jdbc.driver.OracleDriver");
                   con = DriverManager.getConnection("jdbc:oracle:thin:@VALUED-20606295:1521:dbbook","jvending","jvending");
                   java.util.zip.ZipInputStream zip = new java.util.zip.ZipInputStream(new java.io.FileInputStream(new java.io.File("D:\\work\\mywork\\source\\test\\ProvisioningParser\\test.par"))) ;
                   int len = 0 ;
                   java.util.zip.ZipEntry entry = null;
                   do{
                        entry = zip.getNextEntry();
                        if (entry != null){
                             if (entry.getName().equalsIgnoreCase("mg.jpg")){
                                  len = (int)entry.getSize();
                                  break;
                   }while(entry!=null) ;
                   stmt = con.prepareStatement( "Insert into icon (parid, clientbundleid, id, iconfile ) values ( ?,?,?,?)"
                         stmt.setString(1,"101");
                         stmt.setString(2,"101");
                         stmt.setInt(3,1);                    
                         stmt.setBinaryStream( 4, zip, len);
                   stmt.setQueryTimeout(0);
                   stmt.executeUpdate();
                   con.close();               
              catch(Exception e){
                   e.printStackTrace();
              }Thanks,
    Rashmi

    As a guess what you are doing with that zip stuff is very odd.
    You do realize that it is just going to put some binary data into the blob right? And the methods that is going to use will not necessarily create a 'complete' zip file?
    If you want a zip file then just load the file, dont use the zip classes.
    And if you want part of a zip file, (and want to store the parts as a zip) then extract it from the file and create another zip entity using a byte stream rather than a file.
    Finally I suspect your error with the blob occurs because you do not close the statement. But at any rate you should figure out how to do the blob code independent of the zip stuff.
    And what oracle driver version are you using? Some of the older ones need oracle specific handling for blobs.

Maybe you are looking for

  • Installation and compatibility issues with photoshop CS4 - Win 8

    I recently purchased a new computer with Windows 8. I am experiencing issues when attempting to install the downloaded and upgrade copy of photoshop CS4. Initially unpacking the software presented issues, but I believe they've been resolved - specifi

  • Mini DV issues

    Hi I have a Canon HV10 which after a year has just stopped playing back. I have taken it to be repaired but if it can't be I have a number of problems.Even if it can be I have a problem as we go to Galapagos in 3 weeks and the repair situation will n

  • Email monitor for permanent connection.

    I am trying to set up my monitor to send an email to alert me when it detects movement. I have filled out the fields. I have a permanent broadband cable connection. Not dial up. When I try to select test email it tries to dial a connection. Doesn't r

  • File check in broken in SPD 13

    Still works on a little (32bit) netbook with W7, but not on my gallumpin' 64 bit W7 Enterprise work desktop. I can check out okay but can only check in via browser or content/structure. It's a real pain.

  • Error While copying the Planning version : S001 001 doesnt exist in P44V

    Hi Leads, I am trying to copy the planning version for S001 (Version - 001), from the Transaction MC8V. But, it is giving error sayin "S001 001 doesn't exist in P44V". How can I solve this issue. Please do suggest. Thanks, Sandeep