How do I read directly from file into byte array

I am reading an image from a file into a BuffertedImage then writing it out again into an array of bytes which I store and use later on in the program. Currently Im doing this in two stages is there a way to do it it one go to speed things up.
try
            //Read File Contents into a Buffered Image
            /** BUG 4705399: There was a problem with some jpegs taking ages to load turns out to be
             * (at least partially) a problem with non-standard colour models, which is why we set the
             * destination colour model. The side effect should be standard colour model in subsequent reading.
            BufferedImage bi = null;
            ImageReader ir = null;
            ImageInputStream stream =  ImageIO.createImageInputStream(new File(path));
            final Iterator i = ImageIO.getImageReaders(stream);
            if (i.hasNext())
                ir = (ImageReader) i.next();
                ir.setInput(stream);
                ImageReadParam param = ir.getDefaultReadParam();
                ImageTypeSpecifier typeToUse = null;
                for (Iterator i2 = ir.getImageTypes(0); i2.hasNext();)
                    ImageTypeSpecifier type = (ImageTypeSpecifier) i2.next();
                    if (type.getColorModel().getColorSpace().isCS_sRGB())
                        typeToUse = type;
                if (typeToUse != null)
                    param.setDestinationType(typeToUse);
                bi = ir.read(0, param);
                //ir.dispose(); seem to reference this in write
                //stream.close();
            //Write Buffered Image to Byte ArrayOutput Stream
            if (bi != null)
                //Convert to byte array
                final ByteArrayOutputStream output = new ByteArrayOutputStream();
                //Try and find corresponding writer for reader but if not possible
                //we use JPG (which is always installed) instead.
                final ImageWriter iw = ImageIO.getImageWriter(ir);
                if (iw != null)
                    if (ImageIO.write(bi, ir.getFormatName(), new DataOutputStream(output)) == false)
                        MainWindow.logger.warning("Unable to Write Image");
                else
                    if (ImageIO.write(bi, "JPG", new DataOutputStream(output)) == false)
                        MainWindow.logger.warning("Warning Unable to Write Image as JPEG");
                //Add to image list
                final byte[] imageData = output.toByteArray();
                Images.addImage(imageData);
              

If you don't need to manipulate the image in any way I would suggest you just read the image file directly into a byte array (without ImageReader) and then create the BufferedImage from that byte array.

Similar Messages

  • How can i read local excel file into internal table in webdynpro for abap a

    Could someone tell me how How can i read local excel file into an internal table in webdynpro for abap application.
    thank u for your reply

    Deep,
    File manuplations...............................
    1. At the presentation level:
    ->GUI_UPLOAD
    ->GUI_DOWNLOAD
    ->CL_GUI_FRONTEND
    2. At the application server level:
    ->OPEN DATASET : open a file in the application server for reading or writing.
    ->READ DATASET : used to read from a file on the application server that has been opened for reading
    -> TRANSFER DATASET : writing data to a file.
    -> CLOSE DATASET : closes the file
    -> DELETE DATASET : delete file
    If file is on the local PC,use the function module GUI_UPLOAD to upload it into an internal table by passing the given parameters......
    call function 'GUI_UPLOAD'
    exporting
    filename = p_file
    filetype = 'ASC'
    has_field_separator = '#'
    tables
    data_tab = t_data
    p_file : excel file path.
    t_data : internal table
    <b>reward points if useful.</b>
    regards,
    Vinod Samuel.

  • Reading from file into an array

    Hello, new to Java and we need to modify a mortgage calculator to read interest rate from a file into an array and not have them hard coded in the program. I have read many post on how to perform this but am lost on where to put the new code and format. Here is my code and I hope I posted this right.
    import javax.swing.*;                                              // Imports the Main Swing Package                                   
    import javax.swing.event.*;
    import javax.swing.text.*;                                          // Used for  Text Box Caret Position
    import java.awt.*;                                                // Imports the main AWT Package
    import java.awt.event.*;                                         // Event handling class are defined here
    import java.text.NumberFormat;
    import java.text.*;                                              // Imports the Main Text Package
    import java.util.*;                                              // Imports the Main Utility Package
    public class mortgageCalculator1 extends JFrame implements ActionListener             // Creates class mortgageCalculator
        JLabel AmountLabel = new JLabel("   Enter Mortgage Amount:$ ");                   // Declares Mortgage Amount Label
        JTextField mortgageAmount = new JTextField(10);                                     // Declares Mortgage Amount Text Field
        JButton IntandTerm1B = new JButton("7 years at 5.35%");                    // Declares 1st Mortgage Term and Interest Rate
        JButton IntandTerm2B = new JButton("15 years at 5.50%");                    // Declares 2nd Mortgage Term and Interest Rate
        JButton IntandTerm3B = new JButton("30 years at 5.75%");                    // Declares 3rd Mortgage Term and Interest Rate
        JLabel PaymentLabel = new JLabel("   Monthly Payment: ");                     // Declares Monthly Payment Label
        JTextField monthlyPayment = new JTextField(10);                          // Declares Monthly Payment Text Field
        JButton exitButton = new JButton("Exit");                              // Declares Exit Button
        JButton newcalcButton = new JButton("New Calculation");                     // Declares New Calculation Button
        JTextArea mortgageTable = new JTextArea(35,65);                         // Declares Mortgage Table Area
        JScrollPane scroll = new JScrollPane(mortgageTable);                         // Declares ScrollPane and puts the Mortgage Table inside
        public mortgageCalculator1()                                        // Creates Method
             super("MORTGAGE CALCULATOR");                              // Title of Frame
             JMenuBar mb = new JMenuBar();                                   // Cretes Menu Bar
                JMenu fileMenu = new JMenu("File");                                 // Creates File Menu
             fileMenu.setMnemonic('F');                                      // Enables alt + f to Access File Menu
             JMenuItem exitItem = new JMenuItem("Exit");                     // Creates Exit in File Menu
             fileMenu.add(exitItem);                                   // Adds Exit to File Menu
                 exitItem.addActionListener(new ActionListener()                     // Adds Action Listener to the Exit Item
                     public void actionPerformed(ActionEvent e)                     // Tests to Verify if File->Exit is Pressed
                         System.exit(0);                                // Exits the Programs when File->Exit is Pressed
                mb.add(fileMenu);                                      // Adds the File Menu
                setJMenuBar(mb);                              
         setSize(600, 400);                                        // Sets Size of Frame
            setLocation(200,200);                                         // Sets the Location of the Window  
         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);                                  // Command on how to close frame
         JPanel pane = new JPanel();                                   // Declares the JPanel
         pane.setLayout(new BoxLayout(pane, BoxLayout.Y_AXIS));                          // Sets Panel Layout to BoxLayout
         Container grid = getContentPane();                               // Declares a Container called grid
         grid.setLayout(new GridLayout(4,3,5,5));                          // Sets grid Layout to GridLayout
         pane.add(grid);                                             // Adds the grid to the Panel
         pane.add(scroll);                                        // Addes the scrollPane to the Panel
            grid.setBackground(Color.yellow);                              // Set grid color to Yellow
         setCursor(new Cursor(Cursor.HAND_CURSOR));                         // Makes the cursor look like a hand
         mortgageAmount.setBackground(Color.black);                         // Sets mortgageAmount JPanel JTextField Background Color
            mortgageAmount.setForeground(Color.white);                         // Sets mortgageAmount JPanel JTextField Foreground Color
         mortgageAmount.setCaretColor(Color.white);                         // Sets mortgageAmount JPanel JTextField Caret Color
         mortgageAmount.setFont(new Font("Lucida Sans Typewriter", Font.PLAIN, 18));     // Sets mortgageAmount JPanel JTextField Font
         monthlyPayment.setBackground(Color.black);                         // Sets monthlyPayment JPanel JTextField Background Color
         monthlyPayment.setForeground(Color.white);                         // Sets monthlyPayment JPanel JTextField Foreground Color
            monthlyPayment.setFont(new Font("Lucida Sans Typewriter", Font.PLAIN, 18));     // Sets monthlyPayment JPanel JTextField Font
         mortgageTable.setBackground(Color.yellow);                         // Sets mortgageTable JTextArea Background Color
         mortgageTable.setForeground(Color.black);                         // Sets mortgageTable JTextArea Foreground Color
         mortgageTable.setFont(new Font("Arial", Font.PLAIN, 18));               // Sets JTextArea Font
         grid.add(AmountLabel);                                        // Adds the Mortgage Amount Label
         grid.add(mortgageAmount);                                   // Adds the Mortgage Amount Text Field
         grid.add(IntandTerm1B);                                        // Adds 1st Loan and Rate Button
         grid.add(PaymentLabel);                                    // Adds the Payment Label
         grid.add(monthlyPayment);                                    // Adds the Monthly Payment Text Field
           monthlyPayment.setEditable(false);                              // Disables editing in this Text Field
            grid.add(IntandTerm2B);                                        // Adds 2nd Loan and Rate Button
            grid.add(exitButton);
         grid.add(newcalcButton);                                    // Adds the New Calc Button
            grid.add(IntandTerm3B);                                        // Adds the Exit Button
         setContentPane(pane);                                          // Enables the Content Pane
         setVisible(true);                                          // Sets JPanel to be Visable
         exitButton.addActionListener(this);                                // Adds Action Listener to the Exit Button
         newcalcButton.addActionListener(this);                            // Adds Action Listener to the New Calc Button
            IntandTerm1B.addActionListener(this);                              // Adds Action Listener to the 1st loan Button
         IntandTerm2B.addActionListener(this);                              // Adds Action Listener to the 2nd loan Button
         IntandTerm3B.addActionListener(this);                               // Adds Action Listener to the 3rd loan Button
         mortgageAmount.addActionListener(this);                              // Adds Action Listener to the Mortgage  Amount Text Field
         monthlyPayment.addActionListener(this);                              // Adds Action Listener to the Monthly payment Text Field
        public void actionPerformed(ActionEvent e)                               // Tests to Verify Which Button is Pressed
            Object command = e.getSource();                                                 // Enables command to get data
            if (command == exitButton) //sets exitButton                         // Activates the Exit Button
                System.exit(0);  // Exits from exit button                         // Exits from exit button
            int loanTerm = 0;                                             // Declares loanTerm
            if (command == IntandTerm1B)                                   // Activates the 1st Loan Button
                loanTerm = 0;                                        // Sets 1st value of Array
            if (command == IntandTerm2B)                                   // Activates the 2nd Loan Button
                loanTerm = 1;                                        // Sets 2nd value of Array
            if (command == IntandTerm3B)                                   // Activates the 3rd Loan Button
             loanTerm = 2;                                        // Sets 3rd value of Array
                double mortgage = 0;                                   // Declares and Initializes mortgage
             double rate = 0;                                        // Declares and Initializes rate                                        
             double [][] loans = {{7, 5.35}, {15, 5.50}, {30, 5.75},};                 // Array Data for Calculation
                    try
                        mortgage = Double.parseDouble(mortgageAmount.getText());            // Gets user input from mortgageAmount Text Field
                      catch (NumberFormatException nfe)                          // Checks for correct number fformatting of user input
                       JOptionPane.showMessageDialog (this, "Error! Invalid input!");      // Outputs error if number is wrong format or nothing is entered
                       return;
             double interestRate = loans [loanTerm][1];                         // Sets interestRate amount
             double intRate = (interestRate / 100) / 12;                         // Calculates Interst Rate     
                double loanTermMonths = loans [loanTerm] [0];                    // Calculates Loan Term in Months
                int months = (int)loanTermMonths * 12;                          // Converts Loan Term to Months
                double interestRateMonthly = (intRate / 12);                                // monthly interst rate
             double payment = mortgage * intRate / (1 - (Math.pow(1/(1 + intRate), months)));    // Calculation for Monthly payment
                double remainingLoanBalance = mortgage;                              // Sets Reamaining Balance
                double monthlyPaymentInterest = 0;                                       // holds current interest payment
                double monthlyPaymentPrincipal = 0;                                    // holds current principal payment
                NumberFormat myCurrencyFormatter = NumberFormat.getCurrencyInstance(Locale.US);     // Number formatter to format output in table
                monthlyPayment.setText(myCurrencyFormatter.format(payment));
                mortgageTable.setText("Month\tPrincipal\tInterest\tEnding Balance\n" +                // Formats morgageTable Header
                                      "---------\t----------\t------------\t---------------------\n");
                    for (;months > 0 ; months -- )
                     monthlyPaymentInterest = (remainingLoanBalance * intRate);               // Calculation for Monthly Payment Toward Interest
                     //Calculate H = R x I
                     monthlyPaymentPrincipal = (payment - monthlyPaymentInterest);          // Calculation for Monthly Payment Toward Principal
                     //Calculate C = P - H
                  remainingLoanBalance = (remainingLoanBalance - monthlyPaymentPrincipal);     // Calculation for Reamining loan Balance
                  // Calculate R = R - C
                  // H = monthlyPaymentInterest
                  // R = remainingLoanBalance
                  // P = payment
                  // C = monthlyPaymentPrincipal
                  // I = interestRateMonthly
                  mortgageTable.setCaret (new DefaultCaret());                    // Sets Scroll position to the top left corner
                  mortgageTable.append(String.valueOf(months) + "\t" +               // Pulls in data and formats MortgageTable
                  myCurrencyFormatter.format(monthlyPaymentPrincipal) + "\t" +
                     myCurrencyFormatter.format(monthlyPaymentInterest) + "\t" +
                     myCurrencyFormatter.format(remainingLoanBalance) + "\n");
                           if(command == newcalcButton)                               // Activates the new calculation Button
                         mortgageAmount.setText(null);                         //clears mortgage amount fields
                      monthlyPayment.setText(null);                         //clears monthly payment fields
                            mortgageTable.setText(null);                              //clears mortgage table
    public static void main(String[] args)                               //This is the signature of the entry point of all the desktop apps
         new mortgageCalculator1();
    }

    OK, making a little progress but am still very confused.
    What I have is a file (int&term.dat) with three lines;
    5.75, 30
    5.5, 15
    5.35 ,7
    I have three JButtom that I what to read a seperate line and place the term in a term TextField and a rate in a Rate TextField
    I have added the following code and all it does now is output a black space to the screen; I am working with one Button and Just the rate for now to try and get it to work. I have been looking at the forums, reading the internet and several books to try and figure this out. I think I may be getting closer.
    public static void read()
        String line;
        StringTokenizer tokenizer;
        String rate;
        String term;
        try
            FileReader fr = new FileReader ("int&term.dat");
            BufferedReader inFile = new BufferedReader (fr);
            line = inFile.readLine();
            while (line != null)
            tokenizer = new StringTokenizer(line);
            rate = tokenizer.nextToken();
            line = inFile.readLine();
             inFile.close();
             System.out.println(new String());
             catch (FileNotFoundException exception)
                   System.out.println ("The file was not found.");
              catch (IOException exception)
                    System.out.println (exception);
    }

  • How do I store an Int, a short, and multiple bytes from file in byte array

    I'm attempting to do this for a project but can't figure out how to store the three values in one byte array. This is what i've tried
    public void send(byte[] input)
              // TODO
              ByteArrayInputStream bais = new ByteArrayInputStream(input);
              ByteArrayOutputStream baos = new ByteArrayOutputStream();
              DataOutputStream dos = new DataOutputStream(baos);
              byte[] pData = new byte[100];
              try {
                   dos.writeShort(checkSum);
                   dos.writeInt(nextSeqNum);
                   pData=baos.toByteArray();
                   bais.read(pData);
              } catch (IOException e) {
              DatagramPacket dgp = new DatagramPacket(pData, pData.length);When i set pData=baos.toByteArray() it changes the size and then stops me from being able to read the other 94 bytes into the array to send. Any ideas?

    You don't need the ByteArrayInputStream at all.
    dos.writeShort(checkSum);
    dos.writeInt(nextSeqNum);
    dos.write(input);
    pData = baos.toByteArray();
    When i set pData=baos.toByteArray() it changes the sizeNo, it makes it refer to a new byte[] array containing what you've written to the BAOS. That's what it's supposed to do.

  • Reading large binary files into an array for parsing

    I have a large binary log file, consisting of binary data separted by header flags scattered nonuniformly thorughout the data.  The file size is about 50M Byte.  When I read the file into an array, I get the Labview Memory full error.  The design of this is to read the file in and then parse it fro the flags to determine where to separate the data blocks in the byte stream. 
    There are a few examples that I have read on this site but none seem to give a straight answer for such a simple matter.   Does anyone have an example of how I should approach this?

    I agree with Gerd.  If you are working with binaries, why not use U8 instead of doubles.
    If the file is indeed 50MB, then the array should be expecting 52428800 elements, not 50000000.  So if you read the file in a loop and populate an element at a time, you could run out of memory fast because any additional element insertion above 50000000 may require additional memory allocation of the size above 50000000 (potentially for each iteration).  This is just speculation since I don't see the portion of your code that populates the array.
    Question:  Why do you need an array?  What do you do with the data after you read it?  I agree with Altenbach, 50MB is not that big, so working with a file of such a size should not be a problem.

  • How to pass csv data from file into DLL using TestStand

    Hi,
    We have data files which are of CSV format. Each row contains
    about 9 items of data, and have about 5 rows of this data (ie, 5
    test points) :
    eg
    TErrAdd1,UUT,UUT,STM1E,AU4/FR,PRBS23,BIT,10,60
    TErrAdd2,UUT,UUT,STM4O,AU3/UNFR,PRBS15,B1,20,60
    TErrAdd3,UUT,UUT,STM16O,AU4_16C/UNFR,PRBS9,BIT,7,60
    TErrAdd4,UUT,UUT,STM0E,AU3/UNFR,PRBS20,B2,5,60
    TErrAdd5,UUT,UUT,STM64O,AU4_4C/FR,PRBS11,B1,6,60
    What we want to do is to be able to directly pass each
    row of data to a C/C++ DLL. The DLL fn accepts this
    data as a vector of strings.
    eg.
    void DLLTestFn( vector const & configData )
    However, we can write a wrapper for the DLL as I don't
    think TestStand will know about vectors.
    We don't really want to have to hardcode individial references
    to each item of data in TestStand. Is this possible?
    Just read in a row from a data file, and sent it direct
    to the DLL?

    Hi Richardi,
    the principle is quite simple, however, you still need to use a programming language to make the initial file read.
    Once you've done this, you could have it as an array of strings, and pass this directly to a wrapper DLL, which would then pass the data into a string vector.
    Look up the examples\AccessingArrays\PassingArrayParametersToDll\AccessingArrays.seq
    to see how to do this without passing the sequence context.
    If you've read in the details into a container type structure already, then I've made an example which demonstrates this principle and what you'll need to pass it to a vector. (Similar principle can be used to fill in the container when you read the file in the first place.
    You cannot go directly to a vector, since TestStand doesn't understand them.
    Vector classes are difficult to export polymorphically from a DLL since the template class doesn't export, and needs specifically defining. This is what I'm assuming you're ultimately trying to do. (see ref :
    How to Export STL components inside and outside of a class
    I've used VIsual C++ 6 and TestStand 3.0
    Please let me know if this helps to answer your query.
    Thanks
    Sacha Emery
    National Instruments (UK)
    // it takes almost no time to rate an answer
    Attachments:
    for hannah vectors.zip ‏1619 KB

  • How to re-read metadata from file in Photoshop Elements 11 Organizer?

    I am currently testing Lightroom 4 and Photoshop Elements 11 as a replacement for my old softwarestack due to a new DSLR.
    In Lightroom I can read and write metadata directly from/to file. In Photoshop Elements Organizer I have found an option to write tags to files, but none to re-read the metadata after the files has been imported to the catalog.
    I would like to use Lightroom as primary organizer for import/tagging/basic corrections. But Lightroom does not have some nifty things like face/person recognition and SmartTags, so I need the Photoshop Elements Organizer to do that. The target workflow would be:
    DSLR -> Import to -> Lightroom -> tagging -> basic corrections -> write tags to file in Lightroom -> import to PSE organizer -> person recognition -> smart tags -> image edits -> write tags to files in PSE organizer ==> tags can now be re-read in Lightroom, so I get the PSE organizer changes to Lightroom.
    And that is the problem: If changes were made after this workflow in Lightroom, PSE Organizer does not know that until I can re-read the metadata from the files. If I press "write tags to file" in PSE organizer all newer Lightroom tags will be overwritten with the old tags from PSE organizer.
    Does anyone knows a solution for this problem? Or should I file a feature request for both programs?

      You can now do a lot more in the metadata panel in PSE 11. If you select a thumbnail in Organizer and click the three small dots it will bring up a dialog for the metadata fields. To add information to many photos all at once, select all the thumbnails, click the information tab and then click the button marked Add IPTC information. You can then choose to append new information to all of the selected items or to overwrite.
    See image below

  • How do I convert an image file into an array?

    I am using LabVIEW v.6.0.2
    I have no NI IMAQ device or IMAQ card, also no Vision
    The image file I have can be saved as a file containing numbers relating to the picels. I want to put these numbers into an array and plot a cross section intensity chart ( I am investigating young's double slits experiment and want to see the interference fringes in graphical form).

    I'm not sure what you're asking.
    In the GRAPHICS palette, there are READ JPEG file, READ BMP file, and READ PNG file VIs. Choose one and together with DRAW FLATTENED PIXMAP and a PICTURE indicator, you can display a picture with two functions and two wires.
    If you have spreadsheet-type data and import it with READ FROM SPREADSHEET FILE (in the File I/O palette), you can plot that directly to an intensity indicator.
    Steve Bird
    Culverson Software - Elegant software that is a pleasure to use.
    Culverson.com
    Blog for (mostly LabVIEW) programmers: Tips And Tricks

  • Method to create Player directly from the mp3 bytes array

    I was checking JMF and didn't find any method to play a mp3 informing its byte array
    Wouldn't it be an interesting method ? Ok, URL is much easier, but I am talking about ID3 files that has sequences of mp3 chuncks in the same file... Anyone knows a way to build a Player from mp3' array of bytes ???

    sergio_abreu wrote:
    Err, Sorry but I desagree.I expected as much
    It seems you didn't understand my question well.Quite possibly
    I think the form I wrote was confusing:
    In +"Anyone knows a way to build a Player from mp3' array of bytes ???+"
    I meant: Anyone knows a way to create a Player or MediaPlayer CLASS from DYNAMIC mp3' array of bytes ???That's even less coherent, to be honest
    Have you seen the structure of an ID3 music file (album) ? It's a collection of mp3 chuncks in only one file.ID3 is simply metadata about a work. It is not "chunks of MP3"
    I have already designed a ID3 class (I called "ID3Info" ) in Java that extracts/shows (dump) all the mp3 from the ID3 file.ID3 isn't a file format. Nor can you extract an MP3 from it
    The thing I would need now is to have some methods in Manager Class from which I could choose which bytes of a generic file I want to load as an mp3 song, that's all.This makes zero sense. Like saying "I need a kettle which will turn furniture into weather"
    It would be nice if there were 2 new different methods:
    1) Player createRealizedPlayer( byte[] songBytes, String fileExtension);
    Arguments: the song byte array and the extension, ex. "mp3"And what would this method do? Where does the byte[] come from? What is in the file, that you also need in order to play the song? How is this - assuming it's possible - easier, better, than just playing the file?
    2) Player createRealizedPlayer( java.net.URL genericFileURL, int beginPosition, int endPosition, String fileExtension);
    Arguments: the URL of a file containing varios mp3 chuncks and the begin / end of the bytes to be loaded as a song and a String to describe the type of file ("mp3" for example)See above
    PS: If you find it interesting, I am willing to contribute to enrich even more the Java Media framework. If you think my ideas are not valid, I just ask someone to send me the jmf source code so that I can alter some classes for my tests only.Why do you need JMF source code? I don't think this magical upside-down-ness is going to enhance anything, to be honest

  • Problem with reading numbers from file into double int array...

    Okay, this is a snippet of my code:
    public void readMap(String file){
            try {
                URL url = getClass().getResource(file);
                System.out.println(url.getPath());
                BufferedReader in = new BufferedReader(new FileReader(url.getPath()));
                String str;
                String[] temp;
                int j=0;
                while ((str = in.readLine()) != null) {
                    temp = str.split(",");
                    for(int i=0;i<temp.length;i++){
                        map[j] = java.lang.Integer.parseInt(temp[i]);
    j++
    in.close();
    } catch (IOException e) {
    System.out.println("Error: "+ e.toString());
    map[][] is a double int array. Now, the code is running through each line of the text file (with each line looking like this: 0,3,6,2,2,3,1,5,2,3,5,2), and I want to put the numbers into a corresponding double int array (which is where map[][] comes in). Now, this code WOULD work, except I need to set the sizes of each array before I start adding, but I don't know how to get the exact sizes.. how can I get around this issue?
    Message was edited by:
    maxfarrar

    You can do a two-dimensional ArrayList? That syntax
    you wrote didn't work.
    I tried doing:
    private ArrayList<ArrayList><Integer>> map;
    Your syntax is just wrong -- or, this forum software has bug in handling angle brackets.
    ArrayList<ArrayList<Integer>>...The closing angle bracket after the second 'ArrayList' is the one generated by the bug. Basically, it should be T<T<T2>> without spaces. Oh, for that matter:
    Arraylist<ArrayList<Integer>>

  • Reading a pdf file from URL into Byte array/ByteBuffer in an applet.

    I'm trying to figure out why this particular snippet of code isn't working for me. I've got an applet which is supposed to read a .pdf and display it with a pdf-renderer library, but for some reason when I read in the .pdf files which sit on my server, they end up as being corrupt. I've tested it by writing the files back out again.
    I've tried viewing the applet in both IE and Firefox and the corrupt files occur. Funny thing is, when I trying viewing the applet in Safari (for Windows), the file is actually fine! I understand the JVM might be different, but I am still lost. I've compiled in Java 1.5. JVMs are 1.6. The snippet which reads the file is below.
    public static ByteBuffer getAsByteArray(URL url) throws IOException {
            ByteArrayOutputStream tmpOut = new ByteArrayOutputStream();
            URLConnection connection = url.openConnection();
            int contentLength = connection.getContentLength();
            InputStream in = url.openStream();
            byte[] buf = new byte[512];
            int len;
            while (true) {
                len = in.read(buf);
                if (len == -1) {
                    break;
                tmpOut.write(buf, 0, len);
            tmpOut.close();
            ByteBuffer bb = ByteBuffer.wrap(tmpOut.toByteArray(), 0,
                                            tmpOut.size());
            //Lines below used to test if file is corrupt
            //FileOutputStream fos = new FileOutputStream("C:\\abc.pdf");
            //fos.write(tmpOut.toByteArray());
            return bb;
    }I must be missing something, and I've been banging my head trying to figure it out. Any help is greatly appreciated. Thanks.

    Keshav.. wrote:
    I too was going through the same problem but I found for some pdfs it worked fine.I didnt get ur solution.Please explain bcoz it may work for every pdfThis thread is over 3 years old and dead. Please open a new thread which provides details of the problem you are having. Link to this thread if you think it is necessary.
    I shall lock this thread.

  • Reading files into an array

    so im new to this and having problems.
    we have to read a .txt file into an array so when a user types a word in a text box it will search the file and reutrn found if the word is there and not found it the word is not there. but it is not reading the text file here is the code so far
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    public class Checker
    // Declares Values in the array
         static String [] anArray = new String[1000];
         // declares variables needed in code later
         int i;
         String s;
         static int count = 0;
         static String b;
         static JTextArea j = new JTextArea();
         public void readFile() throws IOException{
         File inFile = new File("words.txt");
         FileReader fileReader = new FileReader(inFile);
    BufferedReader bufReader = new BufferedReader(fileReader);
    while (true){
    b = bufReader.readLine();
    anArray[count] = b;
    count++;
    if(b==null) throw new EOFException("Hello, end of file reached");
    j.append(b);
    j.append("\n");
         // public static void main(String args[]){
         // File outFile = new File("words.txt");
         //FileOutputStream outFileStream = new FileOutputStream(outFile);
         // PrintWriter outStream = new PrintWriter(outFileStream);
         // outStream.println("help");
    // File inFile = new File("words.txt");
    // FileReader fileReader = new FileReader(inFile);
    // BufferedReader bufReader = new BufferedReader(fileReader);
    /* while (true){
    b = bufReader.readLine();
    anArray[count] = b;
    count++;
    if(b==null) throw new EOFException("Hello, end of file reached");
    j.append(b);
    j.append("\n");
    public String checkword(String Word ) {
    // Tries the code, runs through until an exception is found.
    try {
    for ( i = 0; i < anArray.length; i++)
    if (Word.equals(anArray))
    // If exception is found, throws a new exception
    if (Word.equals(anArray[i])) throw new Exception(); // end if
    } // end if
    } // end for
    } // end try
    catch (Exception ae ) {
    // if the word is found return a message found and its position in array.
    return "Found, at position "+i;
    }// end catch
    // if its not in the array return a not found message
    return "Not found";
         } // end
    } // end
    and the gui class :
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.io.*;
    public class CountDown extends JFrame implements ActionListener
    // Defines the GUI components
    private JTextField Word = new JTextField(9);
    private JButton Guess = new JButton("Enter String");
         private JLabel Message = new JLabel("not found");
         // Creates a new instance of the Checker class.
    Checker ch = new Checker();
    public CountDown() // constructor
    setTitle("Count Down");
    setSize(300,200);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setVisible(true);
    Container c = getContentPane();
    c.setBackground(Color.white);
    c.setLayout(new GridLayout(3,1));
    // Add the components
    c.add(Word);
    c.add(Guess);
    c.add(Message);
    c.add(ch.j);
    // Add action Listener for Button to work
    Guess.addActionListener(this);
    pack();
    setContentPane(c);
    public void actionPerformed(ActionEvent e) {
    // When the button is pressed do this code
    if(e.getSource() == Guess)
    // Looks in the checker class to compare the word user enters, to the words in the array.
    // Returns a message if the word exists with its position in the list or
    // Returns a message if the word does not exisit.
    Message.setText( ch.checkword(Word.getText()));
    public class CountDownA
    public void main(String[] args)
    CountDown Game = new CountDown();
    any help is appriciated asap

    Yuck! I echo jverd's sentiment. Please only post the specific pieces of code that you are having trouble with, and use the forum 'code' tags.
    But to answer your question, I don't see where you're calling the readFile() method from. If you're not calling readFile, that might explain why nothing is being read.
    As for the design of the readFile method, another 'yuck'. heh Don't use exceptions to break out of a loop. If you MUST break out of a loop, use break. But a loop like this doesn't need break. Try something like this:while( (b = bufReader.readLine()) != null)
         anArray[count++] = b;
         j.append(b+"\n");
    }Also, in stead of creating an array of some arbitrary fixed length, I recommend using a collection class such as ArrayList.
    In stead of this:static String [] anArray = new String[1000];
    anArray[count++] = b;it would be better to use something like this:static ArrayList<String> arrayList = new ArrayList<String>();
    arrayList.add(b);

  • How to read sampled data info from a "*.au"file into an array?

    I need to manipulate the sound file directly using DSP, the first step is to read sampled data from "*.au" file into an array. How can I do that? Thanks a lot!!

    There is a file I/O tutorial in the Java Tutorial (google for Java Tutorial). You can read an .au file as bytes like any binary file.
    Or if you are using the Java Sound API, google for java sound api or java audio tutorial etc etc.

  • How to read relevant record type from file into LSMW ?

    Here my req is like this.
    file with 5 records.
    some of records in file are begin with 'AD'.
    i want to read only that records from file while reading data.
    i created one field in source structure with record type filed.
    even i had given this Identifing Field Content:AD
    but after reading data from file its reading all records from file.
    But it should read only record type AB from source file.
    How can we achieve this?
    Thanks in Advance.

    For this do the follwing steps
    goto step 3 Maintain Source Fields
    press the change mode button  after the double click the filed which is pass the AD value
    then it will appier one popup window in this window you have one check box like " selection parameter for import/convert data"
    tick thic chekc box and save it.
    now when you read the data in Step9 , here you find select options there you enter AD* now you will get the only records start with AD.

  • How can one  read a Excel File and Upload into Table using Pl/SQL Code.

    How can one read a Excel File and Upload into Table using Pl/SQL Code.
    1. Excel File is on My PC.
    2. And I want to write a Stored Procedure or Package to do that.
    3. DataBase is on Other Server. Client-Server Environment.
    4. I am Using Toad or PlSql developer tool.

    If you would like to create a package/procedure in order to solve this problem consider using the UTL_FILE in built package, here are a few steps to get you going:
    1. Get your DBA to create directory object in oracle using the following command:
    create directory TEST_DIR as ‘directory_path’;
    Note: This directory is on the server.
    2. Grant read,write on directory directory_object_name to username;
    You can find out the directory_object_name value from dba_directories view if you are using the system user account.
    3. Logon as the user as mentioned above.
    Sample code read plain text file code, you can modify this code to suit your need (i.e. read a csv file)
    function getData(p_filename in varchar2,
    p_filepath in varchar2
    ) RETURN VARCHAR2 is
    input_file utl_file.file_type;
    --declare a buffer to read text data
    input_buffer varchar2(4000);
    begin
    --using the UTL_FILE in built package
    input_file := utl_file.fopen(p_filepath, p_filename, 'R');
    utl_file.get_line(input_file, input_buffer);
    --debug
    --dbms_output.put_line(input_buffer);
    utl_file.fclose(input_file);
    --return data
    return input_buffer;
    end;
    Hope this helps.

Maybe you are looking for

  • Can I use a repeater with a WRT610N?

    I'm very dissatisfied with the range and signal strength of my new WRT610N dual band router compared to the WAP54G Access Point I used before.  Can I configure the Access Point as a repeater for the 2.4 GHz band on the WRT610N if I use the WRT610N as

  • Adobe bridge cs6 unable to open picture and camera raw

    it will crash when open the file. can't use camera raw. I use window 7

  • Mac OS 10.5.6 - Screen saver takes over while playing DVD.

    Since I installed 10.5.6, when I am playing a DVD using the DVD Player, the screen saver takes over the display and I have to disable it in order to continue to see the DVD video. Anyone have any ideas on how to fix this? I have just been disabling t

  • Drag and Drop Out of iPhoto 4

    Hello I am dragging and dropping a fair number of photos from the main roll on my iPhoto to the desktop - it says "copying" but I just want to confirm - if I was delete them from the desktop I am not deleting them from iPhoto? I say this because I'm

  • Load image on mouseover after the page is showed

    hi guys, i have a slideshow with 30 images and it load all the image until show the page but it takes amount 6-7 second..is there a method to load only a thumbnail and show the page and when i click or mouseover on thumbnail load dinamically the imag