Sending a file from Applet to servlet HELP me Please

Sorry, i have the problem this is my code Applet & Servlet but it seems working asynchronously if you have some ideas please reply me i send bytes on outputstream but the inputstream of servlet receive nothing bytes but write my system.out.print on screen server:
URL servletURL = new URL(codebase, "/InviaFile/servlet/Ricevi");
HttpURLConnection urlConnection = (HttpURLConnection) servletURL.openConnection();
urlConnection.setRequestProperty("Content-Type", "application/octet-stream");
urlConnection.setRequestProperty("Content-length", String.valueOf(100));
if(urlConnection.HTTP_BAD_REQUEST == HttpURLConnection.HTTP_BAD_REQUEST){
/*System.out.println("Cattiva Richiesta: "+urlConnection.getContentEncoding());
System.out.println("Tipo di metodo: "+urlConnection.getRequestMethod());
System.out.println("Tipo di Risposta: "+urlConnection.getResponseCode());
System.out.println("Tipo di messaggio: "+urlConnection.getResponseMessage());
System.out.println("Tipo di contenuto: "+urlConnection.getContentType());
System.out.println("Tipo di lunghezza contenuto: "+urlConnection.getContentLength());
System.out.println("Tipo di doinput: "+urlConnection.getDoInput());
System.out.println("Tipo di doouput: "+urlConnection.getDoOutput());
System.out.println("Tipo di URL: "+urlConnection.getURL());
System.out.println("Tipo di propriet� richiesta: "+urlConnection.getRequestProperty("Content-Type"));
System.out.println("Entra if");
DataOutputStream dout = new DataOutputStream(urlConnection.getOutputStream());
InputStream is = urlConnection.getInputStream();
if(ritornaFile("C:/Ms.tif", dout))System.out.println("Finita lettura");
System.out.println("Fine Applet");
}catch(Exception e) { System.err.println(e.getMessage());e.printStackTrace();}
public boolean ritornaFile(String file, OutputStream ots)throws Exception{
FileInputStream f = null;
f = new FileInputStream(file);
byte[] buf = new byte[4 * 1024];
int byteLetti;
while((byteLetti = != -1){ots.writeByte(buf, 0, byteLetti);ots.flush();
while((byteLetti = != -1){ots.write(byteLetti);ots.flush();
System.out.println("byteLetti= "+byteLetti);
return true;
}catch(Exception ex){
return false;
if(f != null)f.close();
HttpSession ses = request.getSession(true);
System.out.println("Passa servlet "+request.getMethod());
System.out.println("Passa servlet "+ses.getId());
ServletInputStream servletinputstream = request.getInputStream();
DataInputStream dis = new DataInputStream(request.getInputStream());
int c = dis.available();
//ServletOutputStream servletoutputstream
System.out.println("URI= "+request.getRequestURI());
System.out.println("pathTranslated: "+request.getPathTranslated());
System.out.println("RemoteUser: "+request.getRemoteUser());
System.out.println("UserInRole: "+String.valueOf(request.isUserInRole("")));
System.out.println("pathInfo: "+request.getPathInfo());
System.out.println("Protocollo: "+request.getProtocol());
int i = request.getContentLength();
System.out.println("i: "+i);
ritornaFile(servletinputstream, "C:"+File.separator+"Pluto.tif");
System.out.println("GetMimeType= "+getServletContext().getMimeType("Ms.tif"));
InputStream is = request.getInputStream();
int in = is.available();
System.out.println("Legge dallo stream in="+in);
DataInputStream diss = new DataInputStream(servletinputstream);
int ins =;
System.out.println("Legge dallo stream ins="+ins);
int disins = diss.available();
System.out.println("Legge dallo stream disins="+disins);
System.out.println("Fine Servlet");
catch(Exception exception) {
System.out.println("IOException occured in the Server: " + exception.getMessage());exception.printStackTrace();
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, {
processRequest(request, response);
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, {
processRequest(request, response);
/** Returns a short description of the servlet.
public String getServletInfo() {
return "Short description";
public void ritornaFile(InputStream its, String fileDest )throws Exception{
FileOutputStream f = null;
f = new FileOutputStream(fileDest);
byte[] buf = new byte[2 * 1024];
int byteLetti;
while((byteLetti = != -1){
f.write(buf, 0, byteLetti);
}catch(Exception ex){
if(f != null)f.close();

Hi all,
Can anyone help me.I am trying to send an audio file from a applet to servlet with HTTP method(no raw sockets), also the servlet shld be able to save the file on the server.Any suggestions welcome.USing audiostream class from javax.sound.sampled.
The part of applet code which calls servlet is :
URL url = new URL("http://" + host + "/" + context + "/servlet/UserUpdateWorkLogAudio?userid=" + userId.replace(' ', '+') + "&FileName=" + filename.replace(' ', '+'));
URLConnection myConnection = url.openConnection();
urlConnection.setRequestProperty("Content-Type", "application/octet-stream");
out = new BufferedOutputStream(myConnection.getOutputStream());
AudioSystem.write(audioInputStream, fileType,out); // IS THIS RIGHT APPROACH?
************************end of applet code**********************
************************servlet code******************************
{BufferedInputStream in = new BufferedInputStream(request.getInputStream());
????????What code shld i write here to get the audio file stream
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(filename));

Similar Messages

  • Sending xml file from client to servlet

    I am writing the server component of an applcation, such that it will receive xml files from the clients(standalone application similar to javaSwing stuff but it's coded in C#), and the servlet will have to extract the data from the xml file and update the mySql database. it will also fulfill the client's request for xmlFiles (and extract data from DB, format to xml file and send back to client)
    I'm new to implementing the servlet receiving files from clients so would need some help.
    I've got 3 questions to ask:
    1) How does the servlet receive/returns the xml file from the client as a series of httpPost request/response. Do i send a File or the file's contents as a String to/from the client?
    2) Is it also a must to use socket for the file transfers? I have read in other posts about sockets as well as HttpURLConnection but i don't quite understand.
    3) When I send a file back to the client(client is standalone application written in C# whereas server is coded in java), what do i specify for the HttpResponse.setContentType() in my servlet? (i'm returning the xml file to client)
    Would really appreciate for any help rendered. If you have any useful links, would appreciate them too. Thanks a lot.

    I've got 3 questions to ask:
    1) How does the servlet receive/returns the xml file
    from the client as a series of httpPost
    request/response. Do i send a File or the file's
    contents as a String to/from the client?The server will listen on some port for requests. The client has to open a socket to this server to send the file as string to the server.
    2) Is it also a must to use socket for the file
    transfers? I have read in other posts about sockets as
    well as HttpURLConnection but i don't quite
    understand.You use HttpURLConnection to make a request using the http protocol, instead of opening a socket and then writing the html headers yourself.
    3) When I send a file back to the client(client is
    standalone application written in C# whereas server is
    coded in java), what do i specify for the
    HttpResponse.setContentType() in my servlet? (i'm
    returning the xml file to client)Its up to your receiving program how to interpret this though, so you probably dont need this.

  • Uploading large files from applet to servlet throws out of memory error

    I have a java applet that needs to upload files from a client machine
    to a web server using a servlet. the problem i am having is that in
    the current scheme, files larger than 17-20MB throw an out of memory
    error. is there any way we can get around this problem? i will post
    the client and server side code for reference.
    Client Side Code:
    // this class is a client that enables transfer of files from client
    // to server. This client connects to a servlet running on the server
    // and transmits the file.
    public class fileTransferClient
    private static final String FILENAME_HEADER = "fileName";
    private static final String FILELASTMOD_HEADER = "fileLastMod";
    // this method transfers the prescribed file to the server.
    // if the destination directory is "", it transfers the file to
    //11-21-02 Changes : This method now has a new parameter that
    references the item
    //that is being transferred in the import list.
    public static String transferFile(String srcFileName, String
    String destDir, int itemID)
    if (destDir.equals(""))
    destDir = "E:\\FTP\\incoming\\";
    // get the fully qualified filename and the mere filename.
    String fqfn = srcFileName;
    String fname =
    //importTable importer = jbInit.getImportTable();
    // create the file to be uploaded and a connection to
    File fileToUpload = new File(fqfn);
    long fileSize = fileToUpload.length();
    // get last mod of this file.
    // The last mod is sent to the servlet as a header.
    long lastMod = fileToUpload.lastModified();
    String strLastMod = String.valueOf(lastMod);
    URL serverURL = new URL(webadminApplet.strServletURL);
    URLConnection serverCon = serverURL.openConnection();
    // a bunch of connection setup related things.
    // Don't use a cached version of URL connection.
    serverCon.setUseCaches (false);
    serverCon.setDefaultUseCaches (false);
    // set headers and their values.
    serverCon.setRequestProperty(FILENAME_HEADER, destDir +
    serverCon.setRequestProperty(FILELASTMOD_HEADER, strLastMod);
    if (webadminApplet.DEBUG) System.out.println("Connection with
    FTP server established");
    // create file stream and write stream to write file data.
    FileInputStream fis = new FileInputStream(fileToUpload);
    OutputStream os = serverCon.getOutputStream();
    // transfer the file in 4K chunks.
    byte[] buffer = new byte[4096];
    long byteCnt = 0;
    //long percent = 0;
    int newPercent = 0;
    int oldPercent = 0;
    while (true)
    int bytes =;
    byteCnt += bytes;
    //11-21-02 :
    //If itemID is greater than -1 this is an import file
    //otherwise this is a header graphic file transfer.
    if (itemID > -1)
    newPercent = (int) ((double) byteCnt/ (double)
    fileSize * 100.0);
    int diff = newPercent - oldPercent;
    if (newPercent == 0 || diff >= 20)
    oldPercent = newPercent;
    if (bytes < 0) break;
    os.write(buffer, 0, bytes);
    if (webadminApplet.DEBUG) System.out.println("No of bytes
    sent: " + byteCnt);
    // close related streams.
    if (webadminApplet.DEBUG) System.out.println("File
    Transmission complete");
    // find out what the servlet has got to say in response.
    BufferedReader reader = new BufferedReader(
    String line;
    while ((line = reader.readLine()) != null)
    if (webadminApplet.DEBUG) System.out.println(line);
    // close the reader stream from servlet.
    } // end of the big try block.
    catch (Exception e)
    System.out.println("Exception during file transfer:\n" + e);
    return("FTP failed. See Java Console for Errors.");
    } // end of catch block.
    return("File: " + fname + " successfully transferred.");
    } // end of method transferFile().
    } // end of class fileTransferClient
    Server side code:
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.util.*;
    // This servlet class acts as an FTP server to enable transfer of
    // from client side.
    public class FtpServerServlet extends HttpServlet
    String ftpDir = "D:\\pub\\FTP\\";
    private static final String FILENAME_HEADER = "fileName";
    private static final String FILELASTMOD_HEADER = "fileLastMod";
    public void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException,
    doPost(req, resp);
    public void doPost(HttpServletRequest req, HttpServletResponse
    throws ServletException,
    // ### for now enable overwrite by default.
    boolean overwrite = true;
    // get the fileName for this transmission.
    String fileName = req.getHeader(FILENAME_HEADER);
    // also get the last mod of this file.
    String strLastMod = req.getHeader(FILELASTMOD_HEADER);
    String message = "Filename: " + fileName + " saved
    int status = HttpServletResponse.SC_OK;
    System.out.println("fileName from client: " + fileName);
    // if filename is not specified, complain.
    if (fileName == null)
    message = "Filename not specified";
    status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
    // open the file stream for the file about to be transferred.
    File uploadedFile = new File(fileName);
    // check if file already exists - and overwrite if necessary.
    if (uploadedFile.exists())
    if (overwrite)
    // delete the file.
    // ensure the directory is writable - and a new file may be
    if (!uploadedFile.createNewFile())
    message = "Unable to create file on server. FTP failed.";
    status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
    // get the necessary streams for file creation.
    FileOutputStream fos = new FileOutputStream(uploadedFile);
    InputStream is = req.getInputStream();
    // create a buffer. 4K!
    byte[] buffer = new byte[4096];
    // read from input stream and write to file stream.
    int byteCnt = 0;
    while (true)
    int bytes =;
    if (bytes < 0) break;
    byteCnt += bytes;
    // System.out.println(buffer);
    fos.write(buffer, 0, bytes);
    // flush the stream.
    } // end of try block.
    // set last mod date for this file.
    } // end of finally block.
    } // end - the new file may be created on server.
    } // end - we have a valid filename.
    // set response headers.
    if (status != HttpServletResponse.SC_OK)
    getServletContext().log("ERROR: " + message);
    // get output stream.
    PrintWriter out = resp.getWriter();
    } // end of doPost().
    } // end of class FtpServerServlet

    OK - the problem you describe is definitely what's giving you grief.
    The workaround is to use a socket connection and send your own request headers, with the content length filled in. You may have to multi-part mime encode the stream on its way out as well (I'm not about that...).
    You can use the following:
    on your server to get a feel for the format that the request headers need to take.
    - Kevin
    I get the out of Memory Error on the client side. I
    was told that this might be a bug in the URLConnection
    class implementation that basically it wont know the
    content length until all the data has been written to
    the output stream, so it uses an in memory buffer to
    store the data which basically causes memory issues..
    do you think there might be a workaround of any kind..
    or maybe a way that the buffer might be flushed after
    a certain size of file has been uploaded.. ?? do you
    have any ideas?

  • Problem while sending seriailized  object from applet to servlet

    Hi I m having Object communication between Applet and Servlet.
    I m getting error stack trace as
         at$PeekInputStream.readFully(Unknown Source)
         at$BlockDataInputStream.readShort(Unknown Source)
    at Source)
         at<init>(Unknown Source)
    at the line
    ObjectInputStream ois = new ObjectInputStream(conn.getInputStream());
    thanks in advance
    the whole code is as follows....
    public Serializable write(Serializable obj) throws IOException,ClassNotFoundException{
              URLConnection conn = serverURL.openConnection();
              conn.setRequestProperty("Content-Type", "java-internal/"+obj.getClass().getName());
              ObjectOutputStream oos= null;
              oos = new ObjectOutputStream(
                   catch(Exception ee){
                        return the reponse to the client
                   ObjectInputStream ois=null;
    \\this is the line where i m getting the error               
    ois = new ObjectInputStream(conn.getInputStream());
                             return (Serializable)ois.readObject();
                        catch(Exception ee){
                                            System.out.println("Error in Object Client inputstream ");
                                            return null;

    Did anyone find a fix to this problem. I am having a similiar problem. Sometimes I receive an EOFException and othertimes I don't. When I do receive an EOFException I check for available() in the stream and it appears 0 bytes were sent to the Servlet from the Applet.
    I am always open to produce this problem when I use File->New in IE my applet loads on the new page.. and then I navigate to a JSP sitting on the same application server. When I go to the Applet on the initial page and try to send an object to the server I get an EOFException. No idea!

  • Writing Image files from Applet to Servlet

    How to write ImageFiles from an Applet to a Servlet?
    I draw a image on a JComponent in Applet and wanted to save the image file in the server.
    I am unable to write an Image Object to the Servlet as the BufferedImage class is not serialized.
    I tried writing the image to the Servlet output stream and tried reading the data in the servlet and writing the data to a jpg file.
    But the files is not being written as proper jpeg file.
    Any help would be great.

    I get the following exception below when i try to write a Serialized object from an applet to the servlet.
    I copied the serialized class jar file to the tomcat webserver lib folder.
    The serialized class has a BufferedImage object.
    Serialized Class Code
    public class SerializedImage implements Serializable{
         private BufferedImage im = null;
         public SerializedImage() {
         public BufferedImage getSerializedObject() {
              return im;
         public void setSerializedObject((BufferedImage im) {
     = im;
         private BufferedImage fromByteArray(byte[] imagebytes) {
              try {
                   if (imagebytes != null && (imagebytes.length > 0)) {
                        BufferedImage im = ByteArrayInputStream(imagebytes));
                        return im;
                   return null;
              } catch (IOException e) {
                   throw new IllegalArgumentException(e.toString());
         private byte[] toByteArray(BufferedImage o) {
              if(o != null) {
                   BufferedImage image = (BufferedImage)o;
                   ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
                   try {
                        ImageIO.write(image, "jpg", baos);
                   } catch (IOException e) {
                        throw new IllegalStateException(e.toString());
                   byte[] b = baos.toByteArray();
                   return b;
              return new byte[0];
         private void writeObject( out)
         throws IOException {
              byte[] b = toByteArray(im);
         private void readObject( in)
         throws IOException, ClassNotFoundException {
              int length = in.readInt();
              byte[] b = new byte[length];
              im = fromByteArray(b);
    Exception : unexpected block data
    Is there any thing that i am missing or doing wrong?

  • Problem in sending image from applet to servlet

    dear friends,
    i have a need to send an image from applet to servlet via HttpConnection and getting back that image from applet.
    i am struggling with this sice many hours and got tired by searching any post that would help me but haven't got yet.
    i tried using this code but it dosent make any execution sit right. i got NPE at ImageIcon.getDescription() line;
    at applet side
                     FileDialog fd=new FileDialog(jf,"hi");
                     v=new Vector();
                               FileInputStream fis=new FileInputStream(new File(fd.getDirectory()+fd.getFile()));      
                               byte[] imgbuffer=new byte[fis.available()];
                               ImageIcon imgdata=new ImageIcon(imgbuffer);
                                String strwp ="/UASProject/Storeimage";              
                                URL servletURL = new URL(getCodeBase(),strwp);             
                                HttpURLConnection servletCon = (HttpURLConnection)servletURL.openConnection();       
                                servletCon.setRequestProperty("Content-Type", "application/octet-stream");   
                                ObjectOutputStream oboutStream = new ObjectOutputStream(servletCon.getOutputStream());                     
                                //read back from servlet
                                ObjectInputStream inputStream = new ObjectInputStream(servletCon.getInputStream());
                                 v= (Vector)inputStream.readObject();                     
                             //  repaint();
                     }catch(Exception e){e.printStackTrace();}  and this is at servlet side
            try {       
                         Vector v=new Vector();                    
                         ObjectInputStream inputFromjsp = new ObjectInputStream(request.getInputStream());                                      
                          v = (Vector)inputFromjsp.readObject();                                                                                                          
    //sending back to applet
                          ObjectOutputStream oboutstream=new ObjectOutputStream(response.getOutputStream());            
                   } catch (Exception e) {e.printStackTrace();}  i really need your help. please let me out of this headche
    Edited by: san_4u on Nov 24, 2007 1:00 PM

    BalusC wrote:
    san_4u wrote:
    how can i made a HttpClient PostMethod using java applets? as i have experience making request using HttpURLConnection.POST method. ok first of all i am going make a search of this only after i will tell. please be onlineOnce again, see link [3] in my first reply of your former topic.
    yeah! i got the related topic at please look it, i am reading it right now and expecting to be reliable for me.
    well what i got, when request made by html code(stated above) then all the form fields and file data mixed as binary data and available in HttpServletRequest.getinputstream. and at servlet side we have to use a mutipart parser of DiskFileItemFactory class that automatically parse the file data and return a FileItem object cotaing the actual file data,right?.You can also setup the MultipartFilter in your environment and don't >care about it further. Uploaded files will be available as request attributes in the the multipartfilter class file available in jar files(that u suggested to add in yours article) so that i can use it directly? one more thing the import org.apache.commons.httpclient package is not available in these jar files, so where can got it from?
    one mere question..
    i looked somewhere that when we request for a file from webserver using web browser then there is a server that process our request and after retrieving that file from database it sends back as response.
    now i confused that, wheather these webservers are like apache tomcat, IBM's webspher etc those processes these request or there is a unique server that always turned on and process all the request?
    because, suppose in an orgnisation made it's website using its own server then, in fact, all the time it will not turned on its server or yes it will? and a user can make a search for kind of information about this orgnisation at any time.
    hopes, you will have understand my quary, then please let me know the actual process
    Edited by: san_4u on Nov 25, 2007 11:25 AM

  • I recently bought two iMac quad core i5 processor speed 2.5 Ghz. Every time I use Air Drop and I send a file from one iMac to the other, a black curtain drops and I am asked to restart the computer!!! What can I do?

    I recently bought two iMac quad core i5 processor speed 2.5 Ghz. Every time I use Air Drop and I send a file from one iMac to the other, a black curtain drops and I am asked to restart the computer!!! What can I do?

    That's a kernel panic and indicates some sort of problem either with the computer's hardware or software. Visit The XLab FAQs and read the FAQ on diagnosing kernel panics. It would help to post the panic log: Mac OS X- How to log a kernel panic.
    Meanwhile, try booting the computers into Safe Mode then restarting normally. If this is simply a disk repair or cache file problem then this may fix it.
    You can also try creating a new admin account on each computer then booting into the new account. This would help determine if the problem is related to a bad file in the user accounts.

  • Playing an audio file from applet

    Hi friends,
    I have a problem to be solved .
    Please help me.
    I have to play an audio file from applet.When the applet loads it shold start playing .There is a progress bar in the applet it shold alsomove corresponding to that.
    How can i do that.Give me an idea.
    I know nothing about jmf.
    I am using j2sdk1.4,windows 2000 server.

    Forgive my naivety, but i struggle with JAVA! I am desperately trying to create a JAVA plugin to SERVOY and have to date been successful with a few things. Record, Playback, convert to .spx.
    I am really struggling with implementing a rewind and fastforward function of the type you have. I thought it would be easy, but it appears not.
    At the bottom is the complete code from my class that is called by the servoy plugin wrapper,
    i had thought that adding some simple jump 500 ms would have been easy in something like this:
    public AudioStream js_FastForward (AudioStream as) throws IOException {
    !!! Line or two here to move the play head forward !!!
         return as;
    Can you give me any pointers to how i code that fast forward bit.
    many thanks
    package com.d2e.MyPlugin;
    import com.servoy.j2db.scripting.IScriptObject;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.Button;
    import javax.sound.sampled.*;
    import org.xiph.speex.*;
    import org.xiph.speex.spi.*;
    import*;    //import the package
    public class MyPluginProvider implements IScriptObject  {
          public void JSencode()
             throws IOException{
               /** Version of the Speex Encoder */
                final String VERSION = "Java Speex Command Line Encoder v0.9.7 ($Revision: 1.5 $)";
                /** Copyright display String */
                final String COPYRIGHT = "Copyright (C) 2002-2004 Wimba S.A.";
                /** Print level for messages : Print debug information */
                final int DEBUG = 0;
                /** Print level for messages : Print basic information */
                final int INFO  = 1;
                /** Print level for messages : Print only warnings and errors */
                final int WARN  = 2;
                /** Print level for messages : Print only errors */
                final int ERROR = 3;
                int printlevel = INFO;
                /** File format for input or output audio file: Raw */
                final int FILE_FORMAT_RAW  = 0;
                /** File format for input or output audio file: Ogg */
                final int FILE_FORMAT_OGG  = 1;
                /** File format for input or output audio file: Wave */
                final int FILE_FORMAT_WAVE = 2;
                int srcFormat  = FILE_FORMAT_OGG;
                int destFormat = FILE_FORMAT_WAVE;
                int mode       = -1;
                int quality    = 4;
                /** Defines the encoders algorithmic complexity. */
                 int complexity = 3;
                /** Defines the number of frames per speex packet. */
                 int nframes    = 1;
                /** Defines the desired bitrate for the encoded audio. */
                 int bitrate    = -1;
                /** Defines the sampling rate of the audio input. */
                 int sampleRate = -1;
                /** Defines the number of channels of the audio input (1=mono, 2=stereo). */
                 int channels   = 1;
                /** Defines the encoder VBR quality setting (float from 0 to 10). */
                 float vbr_quality = -1;
                /** Defines whether or not to use VBR (Variable Bit Rate). */
                 boolean vbr    = false;
                /** Defines whether or not to use VAD (Voice Activity Detection). */
                 boolean vad    = false;
                /** Defines whether or not to use DTX (Discontinuous Transmission). */
                 boolean dtx    = false;
              //HArd code src format and dest
               // private String srcPath ="junk.wav";
              srcFormat = FILE_FORMAT_WAVE;
              destFormat = FILE_FORMAT_OGG;
             byte[] temp    = new byte[2560]; // stereo UWB requires one to read 2560b
             final int HEADERSIZE = 8;
             final String RIFF      = "RIFF";
             final String WAVE      = "WAVE";
             final String FORMAT    = "fmt ";
             final String DATA      = "data";
             final int WAVE_FORMAT_PCM = 0x0001;
             // Open the input stream
             DataInputStream dis = new DataInputStream(new FileInputStream("junk.wav"));
             // Prepare input stream
           //DP - Sort out the Wave File
               // read the WAVE header
               dis.readFully(temp, 0, HEADERSIZE+4);
               // Read other header chunks
               dis.readFully(temp, 0, HEADERSIZE);
               String chunk = new String(temp, 0, 4);
               int size = readInt(temp, 4);
               while (!chunk.equals(DATA)) {
                 dis.readFully(temp, 0, size);
                 if (chunk.equals(FORMAT)) {
                   typedef struct waveformat_extended_tag {
                   WORD wFormatTag; // format type
                   WORD nChannels; // number of channels (i.e. mono, stereo...)
                   DWORD nSamplesPerSec; // sample rate
                   DWORD nAvgBytesPerSec; // for buffer estimation
                   WORD nBlockAlign; // block size of data
                   WORD wBitsPerSample; // Number of bits per sample of mono data
                   WORD cbSize; // The count in bytes of the extra size
                   } WAVEFORMATEX;
                   if (readShort(temp, 0) != WAVE_FORMAT_PCM) {
                     System.err.println("Not a PCM file");
                   channels = readShort(temp, 2);
                   sampleRate = readInt(temp, 4);
                   if (readShort(temp, 14) != 16) {
                     System.err.println("Not a 16 bit file " + readShort(temp, 18));
                   // Display audio info
                   if (printlevel <= DEBUG) {
                     System.out.println("File Format: PCM wave");
                     System.out.println("Sample Rate: " + sampleRate);
                     System.out.println("Channels: " + channels);
                 dis.readFully(temp, 0, HEADERSIZE);
                 chunk = new String(temp, 0, 4);
                 size = readInt(temp, 4);
               if (printlevel <= DEBUG) System.out.println("Data size: " + size);
           //DP ENd sort wave file 
           //Now Choose the mode , we have a file sampled at 44100
                 mode = 2; // Ultra-wideband
             // Construct a new encoder
             SpeexEncoder speexEncoder = new SpeexEncoder();
             speexEncoder.init(mode, quality, sampleRate, channels);
             if (complexity > 0) {
             if (bitrate > 0) {
             if (vbr) {
               if (vbr_quality > 0) {
             if (vad) {
             if (dtx) {
             // Display info
             // Open the file writer
             AudioFileWriter writer;
             if (destFormat == FILE_FORMAT_OGG) {
               writer = new OggSpeexWriter(mode, sampleRate, channels, nframes, vbr);
             else if (destFormat == FILE_FORMAT_WAVE) {
               nframes = PcmWaveWriter.WAVE_FRAME_SIZES[mode-1][channels-1][quality];
               writer = new PcmWaveWriter(mode, quality, sampleRate, channels, nframes, vbr);
             else {
               writer = new RawWriter();
             writer.writeHeader("Encoded with: " + VERSION);
             int pcmPacketSize = 2 * channels * speexEncoder.getFrameSize();
             try {
               // read until we get to EOF
               while (true) {
                 dis.readFully(temp, 0, nframes*pcmPacketSize);
                 for (int i=0; i<nframes; i++)
                   speexEncoder.processData(temp, i*pcmPacketSize, pcmPacketSize);
                 int encsize = speexEncoder.getProcessedData(temp, 0);
                 if (encsize > 0) {
                   writer.writePacket(temp, 0, encsize);
             catch (EOFException e) {}
            * Converts Little Endian (Windows) bytes to an int (Java uses Big Endian).
            * @param data the data to read.
            * @param offset the offset from which to start reading.
            * @return the integer value of the reassembled bytes.
           protected static int readInt(final byte[] data, final int offset)
             return (data[offset] & 0xff) |
                    ((data[offset+1] & 0xff) <<  8) |
                    ((data[offset+2] & 0xff) << 16) |
                    (data[offset+3] << 24); // no 0xff on the last one to keep the sign
            * Converts Little Endian (Windows) bytes to an short (Java uses Big Endian).
            * @param data the data to read.
            * @param offset the offset from which to start reading.
            * @return the integer value of the reassembled bytes.
           protected static int readShort(final byte[] data, final int offset)
             return (data[offset] & 0xff) |
                    (data[offset+1] << 8); // no 0xff on the last one to keep the sign
         AudioFormat audioFormat;
           TargetDataLine targetDataLine;
         public Class[] getAllReturnedTypes() {
              // TODO Auto-generated method stub
              return null;
         public String[] getParameterNames(String arg0) {
              // TODO Auto-generated method stub
              return null;
         public String getSample(String arg0) {
              // TODO Auto-generated method stub
              return null;
         public String getToolTip(String arg0) {
              // TODO Auto-generated method stub
              return null;
         public boolean isDeprecated(String arg0) {
              // TODO Auto-generated method stub
              return false;
         public String js_Record (String name){
              return "Started Recording " +name;
        public String js_StopRecord (String name) throws IOException{
             //new ActionListener(){
             //   public void actionPerformed(ActionEvent e)
                  //Terminate the capturing of input data
                  // from the microphone.
              //  }//end actionPerformed
             //};//end ActionListener
                 // JSpeexEnc ("junk.wav","output.spx");
              return "Stop Records " +name;
        //Play audio file
        public AudioStream js_Playback (String name) throws IOException{
             InputStream in = new FileInputStream("junk.wav");
             AudioStream as = new AudioStream(in);        
             return as;
        public AudioStream js_ContPlay (AudioStream as) throws IOException {
             return as;
         //Stop Play
        public AudioStream js_Stop_Playback (AudioStream as) throws IOException{
              return as;
         //This method captures audio input from a
        // microphone and saves it in an audio file.
        private void captureAudio(){
            //Get things set up for capture
            audioFormat = getAudioFormat();
            DataLine.Info dataLineInfo =
                                new DataLine.Info(
            targetDataLine = (TargetDataLine)
            //Create a thread to capture the microphone
            // data into an audio file and start the
            // thread running.  It will run until the
            // Stop button is clicked.  This method
            // will return after starting the thread.
            new CaptureThread().start();
          }catch (Exception e) {
          }//end catch
        }//end captureAudio method  
    //  This method creates and returns an
        // AudioFormat object for a given set of format
        // parameters.  If these parameters don't work
        // well for you, try some of the other
        // allowable parameter values, which are shown
        // in comments following the declarations.
        private AudioFormat getAudioFormat(){
          float sampleRate = 44100.0F;
          int sampleSizeInBits = 16;
          int channels = 1;
          boolean signed = true;
          boolean bigEndian = true;
          return new AudioFormat(sampleRate,
        }//end getAudioFormat
        class CaptureThread extends Thread{
               public void run(){
                 AudioFileFormat.Type fileType = null;
                 File audioFile = null;
                 //Set the file type and the file extension
                 // based on the selected radio button.
                  // fileType = AudioFileFormat.Type.AIFC;
                  // audioFile = new File("junk.aifc");
                // }else if(aiffBtn.isSelected()){
                 //  fileType = AudioFileFormat.Type.AIFF;
                 //  audioFile = new File("junk.aif");
                // }else if(auBtn.isSelected()){
                 //  fileType = AudioFileFormat.Type.AU;
                 //  audioFile = new File("");
                // }else if(sndBtn.isSelected()){
                //   fileType = AudioFileFormat.Type.SND;
                 //  audioFile = new File("junk.snd");
                // }else if(waveBtn.isSelected()){
                 fileType = AudioFileFormat.Type.WAVE;
                 audioFile = new File("junk.wav");
                // }//end if
                         new AudioInputStream(targetDataLine),
                 }catch (Exception e){
                 }//end catch
               }//end run
             }//end inner class CaptureThread

  • How do you send a File from the Clinent End To the Server?

    Hi, I'm jut learing Java and am tring to send a file from the Cleints end to the Servers' end, I know how to do this in Php, but its some what different in Java, i know where is a File Class which i can post the information into but for some reason it woudn't work
    <%@ page import=" javax.servlet.*," %>
    String fullname, emailadds, genre, filename;
    fullname = request.getParameter("Name");
    emailadds = request.getParameter("email");
    genre = request.getParameter("genre");
    filename = request.getParameter("clip");
    File file = new File();
    if (file.isFile())
    out.print("File is true");
    out.print("file ain't there");
    just as a tester i tried this to see if file is being read, but it won't compile
    I keep getting this error sign! Have i missed out a lib or somthing?
    \ cannot find symbol
    symbol : constructor File()
    location: class
    File file = new File();

    Sham, dont show your anger... and dont use provocative words...
    Now, coming to your problems.
    your jsp/html should contain some thing like
    <form action="/uploadServlet" method="post">
    <input type="file" name="file"/>
    <input type ="submit" value="upload"/>
    </form>and for servlet code, refer to
    or the easiest way would be to use 'commons-fileupload' api available on

  • How to send a file from FTP to external server

    My requirement is to send a file from FTP to D3(External) server.
    Now I am able to store the file in Appln server.
    I want to send the file created by the program thru FTP to D3 server.
    I know the username,Password,HostID,RFC destination details.
    How to send the file from FTP to D3.
    If u have any program,Plz send it...
    I dont want the function modules name...I want the example code ....
    Thanks in advance.

    Hi Sumi,
    You could do it so that you create a .bat or .cmd script to your server which does your ftp transfer.
    To do this you must use sm69 to create a external operating system command which you can call from FM SXPG_COMMAND_EXECUTE. To SXPG_COMMAND_EXECUTE you the file you need to transfer as a parameter.
    What happens is that your abap program passes the file to windows batch script (.bat .cmd) which will then do the transfer for you.
    Here's a sample of ftp-script for windows:
    echo open IP_ADDRESS_TO_YOUR_SERVER > c:zftp_transfer.ftp
    echo USERNAME>> c:zftp_transfer.ftp
    echo PASSWORD>> c:zftp_transfer.ftp
    echo put YOUR_FILE>> c:zftp_transfer.ftp
    echo quit>> c:zftp_transfer.ftp
    ftp -s:c:zftp_transfer.ftp
    also take a look here for more details:
    Ok, this might be a bit trivial but if your server is unix/aix etc.. Instead of using batch script you must do a shell script.

  • How do I send files from my IMAC via bluetooth to my ne Ipad.  They will not "pair" but they are connected and discoverable.  I send a file from Imac snow leopard OS X 10.6 to the ipad but the failure message says the ipad does not have the ncessary servr

    How do I send files from my IMAC via bluetooth to my new Ipad?  They will not "pair" but they are connected and discoverable.  I send a file from Imac snow leopard OS X 10.6 to the ipadusing bluetooth,  but the failure message says the ipad does not have the necessary services.  What are these?  Do I neeed to have iphoto and ms word to send pix and .doc files?

    File Sharing over Bluetooth is not a feature of iOS devices. iOS does not include the required Bluetooth profiles to allow this. You cannot add this feature, so you may as well stop trying.

  • Sending .xlsx file from ABAP

    Hi Experts,
    How can we send .XLSX file from ABAP.
    I have done as suggested in note 1459896 but it's not working.
    I have added the header table with such value
    concatenate '&SO_FILENAME=' lv_filename into lv_text_line.
      append lv_text_line to lt_att_head.
    passing header table to
    lo_document->add_attachment( exporting i_attachment_type = 'XLS'
                                      i_attachment_subject = 'AttachmentFilename'
                                      i_attachment_size = lv_size
                                      i_attachment_header = lt_att_head
                                      i_att_content_hex    = binary_content ).
    but when I try to open it in SOST it says," file format or extension is not valid " .
    Do you think if I send thsi mail to outlook it will work. ?

    But SAP note says 1459896 , it can be done
    filename = 'attachment.xlsx'
    concatenate '&SO_FILENAME=' lv_filename into lv_text_line.
      append lv_text_line to lt_att_head.
    but still not working.

  • Can we send .csv file from sap srm system to sap pi?

    Hi Experts,
    we have 3 options send the data from sap systems to sap pi.i. e.proxy,idoc and rfc only
    How can we send .csv file from sap srm to sap pi?

    As you know SAP SRM and SAP PI are different boxes.
    *_Option 1:_*
    we need a shared AL11 directory in between SAP SRM and SAP PI (Ask basis to setup shared folder). Place / Populate the file in the folder from SAP SRM and then it can be picked through sender file communication channel.
    In this case you (Basis team) will share one folder which is visible from the AL11 transaction of both the systems (SRM and PI). You will drop .csv file using some report or program from SRM at this location and from PI you can read that file using File communication channel (NFS mode).
    Option 2:
    Setup a FTP at SRM environment and expose some folder which can be accessible from PI. Use sender file communication channel at PI end to pick the file.
    You can use this option incase sharing of folder is not possible (due to network / other constrains). Here FTP server is required to expose any folder as FTP so as it can be accessible from internet (remote location). You need to expose some folder at SRM machine.  You will drop .csv file using some report or program from SRM at this location. Now PI can fetch the file from that location using  sender file communication channel (FTP Mode) providing user credentials.
    Hope it clears now.

  • HT3353 send numbers files from iPad to macbook

    send numbers files from ipad to macbook???

    You can use iCloud to sync files between your iOS & Mountain Lion devices or you could e-mail the file to yourself.

  • Open html file from Applet

    I need to open html file from applet, the html file is placed in my local system, it is not open. the code is below, please can u tell where i did wrong.
    import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
    <applet code="Resource.class" width="400" height="400"></applet>
    public class Resource extends Applet implements ActionListener
    Button b = null;
    public void init(){
    b= new Button("Click");
    public void actionPerformed(ActionEvent ae){
    URL adress = new URL(getDocumentBase(), "html_code.htm");
    getAppletContext().showDocument(adress, "_blank");
    System.out.println("Execut inside"+adress);
    }catch(MalformedURLException e){
    System.out.println("Eror in Display");

    Don't cross post

Maybe you are looking for

  • How to activate a custom datasource of a view

    Hello folks, I'm working on BI 7.0 and ECC 6.0. I've created a z datasource on a view. It appears in RSA6. It is not visible in RSA5 which means I cannot activate it. When I replicate the datasource in BW, it appears as a modified version and not as

  • Import takes more time

    Hi ALL, I am using Oracle 10gR2 on solaris 10. I am doing export and import. I exported one table which is 9.5 GB size and export dump file is 4GB size. I am trying to import that dumpfile into another database. its running more than 15 hours, but st

  • Doubt  about COEP table

    Hi ,    I was looking at table COEP by objnr_n1 and kstar fields and found that it is taking almost 5 to 10mins to execute. Is it the general case with this table or is it only with my sap system. thx Raghu

  • Difference between date datatype

    hi all, We have oracle 10G R2 on windows. we have table called set_1 as SQL> desc set_1; Name                                      Null?    Type SL_NO                                              NUMBER STARTTIME                                      

  • How to check whether two elements are available in an array?

    For example, String str1="2" String str2="3" String [] str3={"2","4","8","9","3"}; Is there any feature available by default to check whether both str1 and str2 are contained in str3? Or we can only compare by doing equals() and a loop?