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"));

Similar Messages

  • 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 :-)

  • 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

  • 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

  • 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;

  • 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.

  • 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.

  • Problem reading image from input Stream

    I'm having a problem reading an image through an input stream. It gives me the error
    Premature end of JPEG file
    sun.awt.image.ImageFormatException: JPEG datastream contains no imageand my code looks like
    public Image getImage(String name, String command){
              if(command.equals(pCode)){
                   Image image=null;
                   System.out.println(name);
                   InputStream is = getClass().getResourceAsStream(name);
                   BufferedInputStream bis = new BufferedInputStream(is);
                    byte[] byBuf =new byte[10000];
                     try {
                        int byteRead = bis.read(byBuf,0,10000);
                   } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                     image = Toolkit.getDefaultToolkit().createImage(byBuf);
                   return image;
              return null;
         }And the string name looks when printed is: usr/images/PRLogo.jpg

    If the image is bigger than 10K, this code will break.
    You can pass an InputStream to javax.imageio.ImageIO.read. That's probably an easier option than trying to do the buffering yourself.

  • 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.

  • 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

  • Problem reading input stream of urlconnection within portal

    Hi,
    This may be a generic server issue rather than portal but since it's my portal app that's displaying the problem I'll post it here.
    Part of my Portal attempts to POST to a remote server to retrieve some search results.
    In environments A & B (both standalone instances) this works fine.
    In environment C this works on the managed instances in the cluster but not the admin instance.
    In environment D (again standalone) it fails, but if I add a managed instance it works from the managed instance.
    The problem I'm seeing is that I get a stuck thread and the thread dump shows it is blocked attempting to read the resulting input from a urlconnection. (Using a buffered input stream).
    I've copied the code to a standalone class that runs fine from the same server(s). I've pasted this code below, the contents of the test() method were copied directly from my webapp (urls changed here for clarity).
    Does anyone know of any securitymanager issues that may cause this?
    Or anything else for that matter?
    Code sample:
    package src.samples;
    import java.io.BufferedReader;
    import java.io.DataOutputStream;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.net.URLConnection;
    public class POSTTest {
         public static boolean test()
         URL url = null;
         try {
         url = new URL
    ("http://hostx:80/myapp/search.html");
         catch (MalformedURLException e)
         e.printStackTrace();
         return false;
         URLConnection urlConn;
         DataOutputStream printout;
         BufferedReader input;
         urlConn = null;
         try {
         urlConn = url.openConnection();
         catch (IOException e)
         e.printStackTrace();
         return false;
         // Let the run-time system (RTS) know that we want input.
         urlConn.setDoInput (true);
         // Let the RTS know that we want to do output.
         urlConn.setDoOutput (true);
         // No caching, we want the real thing.
         urlConn.setUseCaches (false);
         // Specify the content type.
         urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
         // Send POST output (this is a POST because we write then read as per the JDK Javadoc)
         printout = null;
         String body = "";
         try {
         System.out.println("url=" + url.toString());
         printout = new DataOutputStream (urlConn.getOutputStream ());
         String content = "param1=A&param2=B&param3=C&param4=D&param5=E";
         System.out.println("urlParams= " + content);
         printout.writeBytes (content);
         System.out.println("written parameters");
         printout.flush ();
         System.out.println("flushed parameters");
         printout.close ();
         System.out.println("closed parameter stream");
         // <b>Get response data - this is where it blocks indefinitely</b>
         input = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
         System.out.println("got input");
         String str;
         while (null != ((str = input.readLine()))) {
         body = body + str + "\n";
         System.out.println("read input:");
         System.out.println(body);
         input.close ();
         System.out.println("closed input stream");
         catch (IOException e) {
         System.out.println("IOException caught: read failed");
         e.printStackTrace();
         return false;
         return true;
         * @param args
         public static void main(String[] args) {
              System.out.println("Test result= " + test());

    In your recuperar() method, read the FTP input stream into a byte array. (You can do that by copying it to a ByteArrayOutputStream and then getting the byte array from that object.) Then, return a ByteArrayInputStream based on those bytes. After you call completePendingCommand(), of course.
    That's one way.
    PC&#178;

  • Document file or input stream is not set.

    Error sending mail :Exception Thrown
    oracle.apps.xdo.delivery.DeliveryException: Document file or input stream is not set.
    at oracle.apps.xdo.delivery.AbstractDeliveryRequest.submit(AbstractDeliveryRequest.java:1154)
    Delivery manager:
    Can some one tell me what was wrong with this,
    I check my document path I can describe it
    When i send one attachment it works with the same path
    but when I use multiple attachment it gives then error
    Attachment m = new Attachment();
    m.addAttachment("/fapps/oracle/fintstcomn/java/chami/test.pdf","test.pdf","application/pdf");
    m.addAttachment("/fapps/oracle/fintstcomn/java/chami/test2.pdf","test2.pdf","application/pdf");
    delReq.addProperty(DeliveryPropertyDefinitions.SMTP_ATTACHMENT,m);
    Thanks

    Ok. What I needed to do is use the Bursting Engine to send out an email (list of invoices) to sales reps for our company. From what I read I have created an XML Document (Template) and have successfully ran that but it looks like I need to create a control file(bursting)? This control file would need to be saved as an XML? Is this correct?

  • File (Directory) object problem?

    Hi there. My problem is as follows. The method below is supposed to access an pre-existing directory with five previously saved test files, read in those files as account objects, add the objects to an ArrayList, then return the ArrayList. It seems to be able to create a file object representing the directory alright but it then insists that there are no files in the directory! Have I fouled up or is there some subtlety that I'm unware of? I was wondering if the fact that the account files have a .bac extenstion had something to do with it.
    Here's the method, with the two lines of code where I think the problem might lie in bold print:
    public ArrayList retrieveAccounts()throws IOException{
    ArrayList accounts = new ArrayList();
    File accDir = new File("C:" + File.separator + "accounts"); //creates a directory object
    //The following S.o.p statements are for test and maintenance purposes rather than user feedback
    System.out.println("Directory " + accDir.getCanonicalPath() + " opened");
    System.out.println("Confirm Accounts directory exists: " + accDir.exists());
    System.out.println("Directory: " + accDir.isDirectory());
    String [] accFiles = accDir.list(); //gets a list of files in the directory and saves it as a String array
    System.out.println("Number of files in directory: " + accDir.length());
    while(i < accDir.length()){
    filename = accFiles;
    try{
    //open layered input Streams to access the next account file in line
    ObjectInputStream in = new ObjectInputStream(new FileInputStream("C:"+ File.separator + "accounts" + File.separator + filename));
    account = (Account)in.readObject();
    accounts.add(account);
    in.close(); //closes Streams for that particular file
    }catch(IOException e){System.out.println("Filing error as follows: " + e);
                }catch(ClassNotFoundException e){System.out.println("Class not Found. Details: " + e); }
    filename = null; //frees up reference for next file
    i++;//counter increments by one
    return accounts;

    This is what I was trying to do minus the comments and maintence and test code:
    public ArrayList retrieveAccounts()throws IOException{
    ArrayList accounts = new ArrayList();
    File accDir = new File("C:" + File.separator + "accounts");
    String [] accFiles = accDir.list();
    while(i < accDir.length()){
    filename = accFiles;
    try{
    ObjectInputStream in = new ObjectInputStream(new FileInputStream("C:"+ File.separator + "accounts" + File.separator + filename));
    account = (Account)in.readObject();
    accounts.add(account);
    in.close();
    }catch(IOException e){System.out.println("Filing error as follows: " + e);
    }catch(ClassNotFoundException e){System.out.println("Class not Found. Details: " + e); }
    filename = null;
    i++;
    return accounts;
    By the way, your the first Java programmer that I've met that doesn't like comments! :)
    NOTE: Think I may have spotted where I went wrong in my code.
    filename = accFiles;
    Forgot to point it at the specific element of the array, like so:
    filename = accFiles[i];
    Thanks for your help!

Maybe you are looking for

  • How to download pics from email attachment​s to photogalle​ry in windows 8.1

    I need help! I take pics on my phone..send them to my gmail and then download the attachments to my photos..this worked GREAT in Windows 7. I now have Windows 8.1 and HATE it. it gives me the option as usual to open or save the attached picture but b

  • VirtualProvider with Function Module

    Hi,Experts Can anyone tell me how to create a VirtualProvider with Function Module? I have read the How to guide"How to Implement a VirtualProvider with service",but I can't go throw the source code. Please give me a sample test code of yours! Thanks

  • Parameter enque/table_size

    Hello all I would like to know what is the relation between the size of lock table ( defined by parameter "enque/table_size") and number of locks that could be handled. If found only one related information in OSS note 13907 but it didn't helped me.

  • How many command line can 7507 support

    hi i have a problem if i wnat to setup static lu point to ip address i will need two line to define but in my cx site have more than one thousand pc so i need to define client ip x.x.x.x lu 2 client printer ip x.x.x.x 3 plus 1000 pc it will exceed tw

  • ITunes does not sort all of my artist's albums together, how do I fix this?

    I can only find certain albums under the album listing on my iPhone and iPod.  I'd like to have everything listed under the artist's name.  Any suggestions?