Reading only Image Files from a Directory and ignoring the rest

i am wanting to be able to read a directory but only obtain the Image files (ie, gif, jpeg, tiff, png etc) and ignore all other type of files.
i have made a custom ImageFIlter class which extends FileFilter which works for adding a photo singly, as only image files are shown in the JFileChooser. however i am wanting to add a folder of photos at once.
here is the code so far:
File dir;
                    JFileChooser fc = new JFileChooser();
                    fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                    //Handle open button action.
                    int returnVal = fc.showOpenDialog(MainAppGUI.this);
                    if (returnVal == JFileChooser.APPROVE_OPTION) {
                         dir = fc.getSelectedFile();
                         if (dir.isDirectory()) {
                              File[] files = dir.listFiles(new ImageFilter());
                              for (int i = 0; i < files.length; i++) {
                                   if (files.isFile()) {
                                        try {
                                             Photo PhotoAdded = workingCollection.addManyPhotos(files[i], canvas.getChangedMaxDim());
                                             //need to also add it to the relevant vectors, ie
                                             //for mouse over operations, or photos added after
                                             //save.
                                             if(!workingCollection.isDuplicate()){
                                                  photosToCheck.add(photoAdded);
                                                  canvas.addToGrid(photoAdded);
                                                  photosAddedAfterLoad.add(photoAdded);
                                                  canvas.repaint();
                                             else{
                                                  //do nothing as it is already in the vectors.
                                        } catch (Exception er) {
                                             // Do nothing. Bad mp3, don't add.
                                   // recurse through directories
                                   else {
                         } else {
                              try {
                                   throw new IOException(
                                             "Error loading files from a directory: "
                                                       + dir.getAbsolutePath() + " is not a "
                                                       + "directory");
                              } catch (IOException e1) {
                                   // TODO Auto-generated catch block
                                   e1.printStackTrace();
any ideas?

I'm confused.
You already ARE using a FileFilter to only pick up image files. Whats the problem?
If you need to recurse directories you need to change your code only a little.
Write your method
JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
//Handle open button action.
int returnVal = fc.showOpenDialog(MainAppGUI.this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
  dir = fc.getSelectedFile();
if (dir.isDirectory()) {
  scanDirectory(dir);
else{
  // not a directory
public void scanDirectoryForPhotos(File directory){
  // taking your code
if (dir.isDirectory()) {
  File[] files = dir.listFiles(new ImageFilter());
  for (int i = 0; i < files.length; i++) {
    if (files.isFile()) {
// details deleted
// recurse through directories
else {
scanDirectory(files[i]);
Your exception handling is a little strange. You throw an exception only to catch it immediately to print a stack trace? Not exactly the most common handling I've seen. You should probably just throw the exception and let the next level down handle it.
Cheers,
evnafets

Similar Messages

  • Reading only Image files from a directory

    i am wanting to be able to read a directory but only obtain the Image files (ie, gif, jpeg, tiff, png etc) and ignore all other type of files.
    i have made a custom ImageFIlter class which extends FileFilter which works for adding a photo singly, as only image files are shown in the JFileChooser. however i am wanting to add a folder of photos at once.
    here is the code so far:
    File dir;
                        JFileChooser fc = new JFileChooser();
                        fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                        //Handle open button action.
                        int returnVal = fc.showOpenDialog(MainAppGUI.this);
                        if (returnVal == JFileChooser.APPROVE_OPTION) {
                             dir = fc.getSelectedFile();
                             if (dir.isDirectory()) {
                                  File[] files = dir.listFiles(new FileFilter());
                                  for (int i = 0; i < files.length; i++) {
                                       if (files.isFile()) {
                                            try {
                                                 Photo PhotoAdded = workingCollection.addManyPhotos(files[i], canvas.getChangedMaxDim());
                                                 //need to also add it to the relevant vectors, ie
                                                 //for mouse over operations, or photos added after
                                                 //save.
                                                 if(!workingCollection.isDuplicate()){
                                                      photosToCheck.add(photoAdded);
                                                      canvas.addToGrid(photoAdded);
                                                      photosAddedAfterLoad.add(photoAdded);
                                                      canvas.repaint();
                                                 else{
                                                      //do nothing as it is already in the vectors.
                                            } catch (Exception er) {
                                                 // Do nothing. Bad mp3, don't add.
                                       // recurse through directories
                                       else {
                             } else {
                                  try {
                                       throw new IOException(
                                                 "Error loading files from a directory: "
                                                           + dir.getAbsolutePath() + " is not a "
                                                           + "directory");
                                  } catch (IOException e1) {
                                       // TODO Auto-generated catch block
                                       e1.printStackTrace();
    any ideas?

    it shouldnt be new FileFilter() there, it should be new ImageFilter() but it gives a compilation error saying i cannot apply that parameter to the listFiles() method in the File class

  • I want read PDF file from SAP directory and create a spool request or print

    Hi all,
    I want read PDF file from SAP directory and create a spool request or print the pdf through SAP. Can any body  help me in this.
    Also please write to me if its possible to open PDF from SAP directory to adobe pdf reader.
    Thanks in advance,
    Sunny

    Hi Sunny,
    Check these links.
    http://www.sapdevelopment.co.uk/reporting/rep_spooltopdf.htm
    http://www.erpgenie.com/sap/abap/pdf_creation.htm
    http://www.geocities.com/mpioud/Z_EMAIL_ABAP_REPORT.html
    http://www.thespot4sap.com/Articles/SAP_Mail_SO_Object_Send.asp
    http://www.sapdevelopment.co.uk/reporting/email/attach_xls.htm
    Hope this resolves your query.
    Reward all the helpful answers.
    Regards

  • I previously uploaded images onto my desktop to work on in Lightroom 5.2. I worked on a few of the images days ago and just now getting back to them. My problem is I can only access the images I previously worked on and all the rest it says images not ava

    I previously uploaded images onto my desktop to work on in Lightroom 5.2. I worked on a few of the images days ago and just now getting back to them. My problem is I can only access the images I previously worked on and all the rest it says images not available but all the images are still right on my desktop.

    ... and all the rest it says images not available
    Normally this happens because you moved, renamed or deleted these photos (or the folders that contain them) outside of Lightroom. This is how to fix the problem: Adobe Lightroom - Find moved or missing files and folders

  • TS1292 When I scratched the code, the letters came off with. I can read two X, one Z, S, R, and N, the rest are illegible

    When I scratched the code the letters came off with. I can read two X, one Z, S, R, and N, the rest are illegible

    Try here  >   iTunes Store: Invalid, inactive, or illegible codes

  • How use PHP to read image files from a folder and display them in Flex 3 tilelist.

    Hello. I need help on displaying images from a folder dynamically using PHP and display it on FLEX 3 TileList. Im currently able to read the image files from the folder but i don't know how to display them in the TileList. This is my current code
    PHP :
    PHP Code:
    <?php
    //Open images directory
    $imglist = '';
    $dir = dir("C:\Documents and Settings\april09mpsip\My Documents\Flex Builder 3\PHPTEST\src\Assets\images");
    //List files in images directory
    while (($file = $dir->read()) !== false)
    if (eregi("gif", $file) || eregi("jpg", $file) || eregi("png", $file))
    echo "filename: " . $file . "\n";
    $dir->close();
    ?>
    FLEX 3 :
    Code:
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="pic.send();">
    <mx:Script>
    <![CDATA[
    import mx.controls.Alert;
    import mx.events.FlexEvent;
    import mx.rpc.events.FaultEvent;
    import mx.events.ItemClickEvent;
    import mx.rpc.events.ResultEvent;
    public var image:Object;
    private function resultHandler(event:ResultEvent):void
    image = (event.result);
    ta1.text = String(event.result);
    private function faultHandler(event:FaultEvent):void
    ta1.text = "Fault Response from HTTPService call:\n ";
    ]]>
    </mx:Script>
    <mx:TileList x="31" y="22" initialize="init();" dataProvider = "{image}" width="630" height="149"/>
    <mx:String id="phpPicture">http://localhost/php/Picture.php</mx:String>
    <mx:HTTPService id="pic" url="{phpPicture}" method="POST"
    result="{resultHandler(event)}" fault="{faultHandler(event)}"/>
    <mx:TextArea x="136" y="325" width="182" height="221" id="ta1" editable="false"/>
    <mx:Label x="136" y="297" text="List of files in the folder" width="182" height="20" fontWeight="bold" fontSize="13"/>
    </mx:Application>
    Thanks. Need help as soon as possbile. URGENT.

    i have made some changes, in the php part too, and following is the resulting code( i tried it, and found that it works.):
    PHP Code:
    <?php
    echo '<?xml version="1.0" encoding="utf-8"?>';
    ?>
    <root>
    <images>
    <?php
    //Open images directory
    $dir = dir("images");
    //List files in images directory
    while (($file = $dir->read()) !== false)
    if (eregi("gif", $file) || eregi("jpg", $file) || eregi("png", $file))
    echo "<image>" . $file . "</image>"; // i expect you to use the relative path in $dir, not C:\..........
    //$dir->close();
    ?>
    </images>
    </root>
    Flex Code:
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
    layout="absolute"
    creationComplete="callPHP();">
    <mx:Script>
    <![CDATA[
    import mx.rpc.http.HTTPService;
    import mx.controls.Alert;
    import mx.events.FlexEvent;
    import mx.rpc.events.FaultEvent;
    import mx.events.ItemClickEvent;
    import mx.collections.ArrayCollection;
    import mx.rpc.events.ResultEvent;
    [Bindable]
    private var arr:ArrayCollection = new ArrayCollection();
    private function callPHP():void
    var hs:HTTPService = new HTTPService();
    hs.url = 'Picture.php';
    hs.addEventListener( ResultEvent.RESULT, resultHandler );
    hs.addEventListener( FaultEvent.FAULT, faultHandler )
    hs.send();
    private function resultHandler( event:ResultEvent ):void
    arr = event.result.root.images.image as ArrayCollection;
    private function faultHandler( event:FaultEvent ):void
    Alert.show( "Fault Response from HTTPService call:\n " );
    ]]>
    </mx:Script>
    <mx:TileList id="tilelist"
    dataProvider="{arr}">
    <mx:itemRenderer>
    <mx:Component>
    <mx:Image source="images/{data}" />
    </mx:Component>
    </mx:itemRenderer>
    </mx:TileList>
    </mx:Application>

  • Sample code to read a text file from UNIX directory.

    I am using 9i Developer Suite, application server is 9.0.4. I want some help on how to read a flat file from UNIX environment. A sample code could be very helpful.
    In windows, i use this kind of code:-
    I declare an object & then write to a file using these sample staements:-
    file_handle text_io.file_type;
    filename := 'd:\ran\egs\uninvoiced.txt';
    file_handle:=text_io.fopen(filename,'w');
    text_io.put_line(file_handle, 'MOBILE NO '||'COUPON NO ' || 'DATE');
    I hope, my question is clear. Please help in solving the doubt.
    Regards.

    filename := 'd:\ran\egs\uninvoiced.txt';This is a Windows directory, so it won't work on Unix.
    For the rest of the code: see examples in the Forms Builder Online Help.

  • How can I read only text files in a directory.

    I've written a program to read files in a directory but I'd like for it to only read the text files of that directory.
    import java.io.*;
    public class Data {
      public static void main(String[] args) throws IOException {
      String target_dir = "C:\\files";
      File dir = new File(target_dir);
      File[] files = dir.listFiles();
      for (File textfiles : files) {
      if (textfiles.isFile()) {
      BufferedReader inputStream = null;
      try {
      inputStream = new BufferedReader(new FileReader(textfiles));
      String line;
      while ((line = inputStream.readLine()) != null) {
      System.out.println(line);
      } finally {
      if (inputStream != null) {
      inputStream.close();

    You have mentioned you want to read only text files.
    If you are referring to some specific set of extentions, you can filter based on that.
    ex: you want to read only .txt files, you can add an if condition as below :
              if(textfiles.getName().endsWith(".txt")) {
                  // Add your code here
    Cheers
    AJ

  • Removing Exchange 2007 from SBS 2008 (In an Exchange 2010 Coexistance Scenario) - In order to remove 2007 Mailbox Objects from Active Directory and remove the SBS2008 server completely

    I'm trying to remove Exchange 2007 from an SBS 2008 server
    (Server 2008 Standard FE).  My ultimate goal is to completely remove the SBS 2008 Server from the network environment.
    We have an Exchange 2010 Coexistence Scenario and Mailboxes/Public Folders/etc have been moved over to the 2010 mail server, on Server 2008 R2.
    I have moved all Shares, FSMO roles, DHCP, DNS, etc over to their respective servers.  We have two full blown DC's in the environment.
    I'm ready to remove Exchange 2007 from SBS 2008 and DCPROMO the server.  I can NOT seem to find a TechNet article that shows me how
    to proceed in this kind of scenario.  I am trying to use the TechNet article:
    http://technet.microsoft.com/en-us/library/dd728003(v=ws.10).aspx
    This article references Disabling Mailboxes, Removing OAB, Removing Public Folder Databases, then uninstalling Exchange using the Setup Wizard. 
    When I go to Disable Mailboxes I get the following error:
    Microsoft Exchange Error
    Action 'Disable' could not be performed on object 'Username (edited)'.
    Username (edited)
    Failed
    Error:
    Object cannot be saved because its ExchangeVersion property is 0.10 (14.0.100.0), which is not supported by the current version 0.1 (8.0.535.0). You will need a later version of Exchange.
    OK
    I really don't see why I need to Disable Mailboxes, Remove OAB and Public Folder Databases since they have been moved to 2010.  I just want
    to remove Exchange 2007 and DCPROMO this server (actually I just want to remove any lingering Exchange AD Objects referring to the SBS 2008 Server, using the easiest and cleanest method possible).
    Can someone point me in the right direction?
    Thanks!

    Hi,
    Based on your description, it seems that you are in a migration process (migrate SBS 2008 to Windows Server
    2008 R2). Now, you want to remove Exchange Server and demote server. If anything I misunderstand, please don’t hesitate to let me know.
    On current situation, please refer to following articles and check if can help you.
    Transition
    from Small Business Server to Standard Windows Server
    Removing SBS 2008 –
    Step 1: Exchange 2007
    Removing SBS 2008 – Step 2:
    ADCS
    Removing
    SBS 2008 – Step 3: remove from domain / DCPROMO
    Please Note: Since the web site is not hosted by Microsoft, the link may change without notice. Microsoft
    does not guarantee the accuracy of this information.
    Hope this helps.
    Best regards,
    Justin Gu

  • How to open and read many files from a directory and store contents in 2D array?

    I want to make a VI that opens and reads the data from various files contained in a directory (200 files each with 2 columns) and store these in a single 2D array. For file number 1 I want to store the data from both columns in the 2D array, but for files 2 to 200 I only want to store the second column of each file. Can someone please help?

    Hi Nadav,
    Thanks for your help. I have followed your instructions but i cannot get it to work. I used the LIST DIRECTORY to list the files in the directory - that works. However, how do I read each of the 200 files using READ FROM SPREADSHEET FILE without me having to manually select each of the 200 files? So, if I use LIST DIRECTORY to list all 200 files in an array, how do I get each of these to open and store the data in a 2D array? Here is what I have done (File called read_files.VI) Could you please help me? Thank you very much in advance.
    Attachments:
    read_files.vi ‏18 KB

  • Read a xml file from local directory, transform it and put in new local dir

    Hi,
    I have a simple requirement. I have one XML file in d://source folder. I want to read it, transform it and want to put the transformed xml file in new location d://target.
    I am new to OSB. Please help me out to complete the above requirement.
    Thanks in advance.
    Cheers.

    Use a polling file transport proxy service to read the file(d://source folder)
    Do the necessary transformation XML or MFL(if the file is fixed length strings) in the proxy service stages.
    Use a file transport business service to write the file to a directory(d://target).To be called from the proxy service route node.
    http://docs.oracle.com/cd/E17904_01/doc.1111/e15866/transports.htm

  • How to read a XML file from BLOB column and insert in a table - PL/SQL Only

    Hi,
    To make data load more simple to end user instead placing file on the server and use SQL-LOADER, I came up with new idea that using oracle ebusiness suite attachment functionality. that loads a XML file from local PC to a database column(table is fnd_attachments, default data type is BLOB over here).
    I tried with DBMS_LOB and didnt get around.
    Please can anyone tell me how to read the BLOB column using PL/SQL and store the data in a oracle table. Here's the sample XML file and table structure FYI.
    <?xml version="1.0" encoding="UTF-8"?>
    <dataroot xmlns:od="urn:schemas-microsoft-com:officedata" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="Corporate_alloc.xsd" generated="2009-07-07T14:17:49">
    <Corporate_alloc>
    <PKG_CODE>BKCORP</PKG_CODE>
    <PKG_NAME>Corporate Edition - Books</PKG_NAME>
    <DET_CODE>B9780080543758</DET_CODE>
    <DET_NAME>Waves, Tides and Shallow-Water Processes</DET_NAME>
    <ALLOCATION_RATIO>0.000041</ALLOCATION_RATIO>
    </Corporate_alloc>
    <Corporate_alloc>
    <PKG_CODE>BKCORP</PKG_CODE>
    <PKG_NAME>Corporate Edition - Books</PKG_NAME>
    <DET_CODE>B9780080534343</DET_CODE>
    <DET_NAME>Hydrostatically Loaded Structures</DET_NAME>
    <ALLOCATION_RATIO>0.000127</ALLOCATION_RATIO>
    </Corporate_alloc>
    </dataroot>
    CREATE TABLE TEST_XML
    ( PKG_CODE VARCHAR2(50),
    PKG_NAME VARCHAR2(100),
    DET_CODE VARCHAR2(20),
    DET_NAME VARCHAR2(500),
    ALLOCATION_RATIO NUMBER )
    Thanks
    EBV

    In regards to #3, use the COLUMNS functionality of XMLTable instead of using Extract. Two simple examples are
    Re: XML Data - Caliculate fields
    Re: Extractvalue function not recognised

  • Reading only certain files from Movies folder?

    Hello all,
    I have an external hard drive connected to my Time Capsule that is loaded with a bunch of VIDEO_TS folders of all my DVDs, and I have that drive aliased in my "Movies" folder on my MacBook Pro, so when I open Front Row, it points to my external HDD, and everything is hunky-dory.  But I also have other files in this HDD (a bunch of JPG files) that are also being seen by Front Row.  For reasons that are too boring to get into, I don't want to separate the files into different locations, I would like to keep them together.  But my goal is to be able to somehow block Front Row from seeing these JPG files and just display the list of my DVDs instead.  Is there any way to tell my alias to block out the JPGs, or some way to hide the JPGs from that particular alias, or something along those lines?
    Thanks for any help I may get!
    Ben

    The only way I can immediately think of is the way I have arranged it, whereby I don't use an alias of the external HD, but aliases of each individual TS folder.
    That certainly avoids showing non-video files in the Movies folder.

  • How to fetch the image file from oracle database and display it.

    hi... i've inserted the image file into the oracle database... now i want to retreive it and want to display it... can anybody help me... pls

    not a big deal dude... i fetched the image from database and saved it into my local hard disk.. but when tried to open it,ends up with no preview... dont know what d prob is... any idea... i've inserted the image as bytes n trying to fetch it as binary stream.. is that the problem... here im giving my insertion and retireving code.. jus go through it...
    Insertion code:_
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    package PMS;
    import java.io.File;
    import java.io.FileInputStream;
    import java.sql.Blob;
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.SQLException;
    public class Browse_java
    static Connection con=null;
    public static void main(String args[])
    try{
    System.out.println("(browse.java) just entered in to the class");
    con = new PMS.DbConnection().getConnection();
    System.out.println("(browse.java) connection string is"+con);
    PreparedStatement ps = con.prepareStatement("INSERT INTO img_exp VALUES(?,?)");
    System.out.println("(browse.java) prepare statement object is"+ps);
    File file =new File("E:/vanabojanalu-/DSC02095.JPG");
    FileInputStream fs = new FileInputStream(file);
    System.out.println("lenth of file"+file.length());
    byte blob[]=new byte[(byte)file.length()];
    System.out.println("lenth of file"+blob.length);
    fs.read(blob);
    ps.setString(1,"E:/vanabojanalu-/DSC02095.JPG");
    ps.setBytes(2, blob);
    // ps.setBinaryStream(2, fs,(int)file.length());
    System.out.println("(browse.java)length of picture is"+fs.available());
    int i = ps.executeUpdate();
    System.out.println("image inserted successfully"+i);
    catch(Exception e)
    e.printStackTrace();
    finally
    try {
    con.close();
    } catch (SQLException ex) {
    ex.printStackTrace();
    and Retrieving code is:
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    package PMS;
    import java.beans.Statement;
    import java.io.*;
    import java.net.*;
    import java.sql.*;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import oracle.jdbc.OracleResultSet;
    * @author Administrator
    public class view_image2 extends HttpServlet {
    * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
    * @param request servlet request
    * @param response servlet response
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    response.setContentType("image/jpeg");
    //PrintWriter out = response.getWriter();
    try
    javax.servlet.http.HttpServletResponse res=null;;
    int returnValue = 0;
    Connection con = null;
    PreparedStatement stmt = null;
    ResultSet rs = null;
    InputStream in = null;
    OutputStream os = null;
    Blob blob = null;
    //String text;
    //text=request.getParameter("text");
    //Class.forName("com.mysql.jdbc.Driver");
    con=new PMS.DbConnection().getConnection();
    System.out.println("jus entered the class");
    //String query = "SELECT B_IMAGE FROM img_exp where VC_IMG_PATH=?";
    //conn.setAutoCommit(false);
    PreparedStatement pst = con.prepareStatement("select b_image from img_exp where vc_img_path=?");
    System.out.println("before executing the query");
    pst.setString(1,"C:/Documents and Settings/Administrator/Desktop/Leader.jpg");
    rs = pst.executeQuery();
    //System.out.println("status of result set is"+rs.next());
    System.out.println("finished writing the query");
    int i=1;
    if(rs.next())
    System.out.println("in rs") ;
    byte[] byte_image=rs.getBytes(1);
    // byte blob_byte[]= new byte[(byte)blob.length()];
    //System.out.println("length of byte is"+blob_byte);
    //String len1 = (Oracle.sql.blob)rs.getString(1);
    //System.out.println("value of string is"+len1);
    //int len = len1.length();
    //byte [] b = new byte[len];
    //in = rs.getBinaryStream(1);
    int index = in.read(byte_image, 0, byte_image.length);
    System.out.println("value of in and index are"+in+" "+index);
    FileOutputStream outImej = new FileOutputStream("C://"+i+".JPG");
    //FileOutputStream fos = new FileOutputStream (imgFileName);
    BufferedOutputStream bos = new BufferedOutputStream (outImej);
    //byte [] byte_array = new byte [blob_byte.length]; //assuming 512k size; you can vary
    //this size depending upon avlBytes
    //int bytes_read = in.read(blob_byte);
    bos.write(index);
    /*while (index != -1)
    outImej.write(blob_byte, 0, index);
    index = in.read(blob_byte, 0, blob_byte.length);
    //System.out.println("==========================");
    //System.out.println(index);
    //System.out.println(outImej);
    //System.out.println("==========================");
    /*ServletOutputStream sout = response.getOutputStream(outImej);
              for(int n = 0; n < blob_byte.length; n++) {
                   sout.write(blob_byte[n]);
              sout.flush();
              sout.close();*/
    outImej.close();
    //i++;
    else
    returnValue = 1;
    catch(Exception e)
    System.out.println("SQLEXCEPTION : " +e);
    finally {
    //out.close();
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    * Handles the HTTP <code>GET</code> method.
    * @param request servlet request
    * @param response servlet response
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    processRequest(request, response);
    * Handles the HTTP <code>POST</code> method.
    * @param request servlet request
    * @param response servlet response
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    processRequest(request, response);
    * Returns a short description of the servlet.
    public String getServletInfo() {
    return "Short description";
    // </editor-fold>
    }

  • Problem in reading an Image file from a Output Stream.

    I am having problem reading a JPEG file. Actually i am sending JPEG file using UDP from the client. I am using this code to convert to a byte array to transmit the file:
    DataInputStream inStream = new DataInputStream(new FileInputStream("src/Bgamex.jpg"));
    String str1 = inStream.toString();
    byte[] bindata = new byte[65500];
    bindata = str1.getBytes();
    On the server side, I am using these lines to convert the bytes to a file again but it seems to be that its not working. Its making file but with a bigger size & like garbage in it, showing nothing:
    byte[] buf = new byte[65500];
    // receive request
    DatagramPacket packet = new DatagramPacket(buf, buf.length);
    socket.receive(packet);
    buf = packet.getData();
    java.io.OutputStream fos = new java.io.FileOutputStream("Bga.jpg");
    fos.write(buf);
    Could somebody lemme know the problem in converting the file.
    Thanx.

    I propose you to perform this simple test to see by yourself:     final String BIN_FILENAME = "somebytes.bin";
        byte[] bin = {5, 4, 3, 2, 1};
        FileOutputStream out = new FileOutputStream(BIN_FILENAME);
        out.write(bin);
        out.flush();
        out.close();
        byte[] bindata;
        DataInputStream in1 = new DataInputStream(new FileInputStream(BIN_FILENAME));
        String str = in1.toString();
        in1.close();
        bindata = str.getBytes();   
        System.out.print("Bytes read with in1>");
        for (int i=0; i<bindata.length; i++) System.out.print(bindata);
    System.out.println();
    FileInputStream in2 = new FileInputStream(BIN_FILENAME);
    bindata = new byte[65505];
    int bread = in2.read(bindata, 0, in2.available());
    in2.close();
    System.out.print("Bytes read with in2>");
    for (int i=0; i<bread; i++) System.out.print(bindata[i]);
    System.out.println();

Maybe you are looking for