How do I go from byte to int?

I am writing a program which reads a file in, transforms it into a byte array and then extracts information out of the byte array. One of these bits of information is an integer. I am having great trouble actually transforming the byte[] containing the bytes for the integer actually into the integer!
I've Googled and looked around forums and I'm just not sure why it's not working. :s
This is what I have so far:
     private int bytesToInt(byte[] b) {
          int bLen = b.length;
          System.out.println("length: " + bLen);
          int result;
          switch (bLen) {
               case 1: result = (int)b[0] & 0xFF; break;
               //case 2: return b[0]
               default: result = 999; break;
          } // switch
          return result;
     } // bytesToInt()When i run it at the moment, with the integer 5 in the file, it returns 53 instead.. Any help would be much appreciated!

I seem to be going round in circles with this!! I've tried various ways and i'm just not getting it. :s
This is what i've tried:
     private int bytesToInt(byte[] b) throws IOException {
          // takes the bytes specifying the win amount, casts to char and parses to int
          int bLen = b.length;
          char[] ch = null;
          int result = 0;
          // can take numbers up to 999
          switch (bLen) {
               case 1: ch[0] = (char)(b[0] + '0');
               result = Character.digit(ch[0], 10);
               break;
               // case 2: ch[0] = (char)(b[0] + '0'); ch[1] = (char)(b[1] + '0'); break;
               // case 3:  ch[0] = (char)(b[0] + '0'); ch[1] = (char)(b[1] + '0'); ch[2] = (char)(b[2] + '0'); break;
               default: result = 0; break;
          } // switch
          return result;
     } // bytesToInt()which gave me the error:
Exception in thread "main" java.lang.NullPointerException
     at lod.LODMapLoader2.bytesToInt(LODMapLoader2.java:112)
     at lod.LODMapLoader2.getWinAmount(LODMapLoader2.java:99)
     at lod.LODMapLoader2.main(LODMapLoader2.java:181)
Vanessa-Clarkes-MacBook:src vrc20$ javac lod/LODMapLoader2.java
Vanessa-Clarkes-MacBook:src vrc20$ java lod/LODMapLoader2 testFile
and so then i tried to simplify it and only consider if i was to be given one int..
     private int bytesToInt(byte[] b) throws IOException {
          // takes the bytes specifying the win amount, casts to char and parses to int
          int bLen = b.length;
          char ch;
          int result = 0;
          // can take numbers up to 9
          ch = (char)(b[0] + '0');
          result = (int)ch - '0';
          return result;
     } // bytesToInt()This ended up giving me 53 again. I'm feeling slightly frustrated.. What have I missed?

Similar Messages

  • How to create short from byte[2]

    Hi, my problem is, that once i wrote application which was able to add echo to a wav file in c++ :
    #include<iostream>
    #include<string>
    #include<cstdio>
    using namespace std;
    int write=0;
    int read=0;
    void insert(short int * tablica,short int element,int value);
    void read_out(short int * liczba,short int * tablica,int value);
    int main(){
    FILE * file_in;
    FILE * file_out;
    char header[44];
    file_in = fopen("output.wav","rb");
    cout<<"wprowadz dlugosc echa: "<<endl;
    int echo;
    int count=0;
    cin>>echo;
    short int * fifo=new short int[echo];
    short int sample;
    short int temp;
    file_out = fopen("new.wav","wb");
    fread(header,44,1,file_in);
    fwrite(header,44,1,file_out);
    for(int p=0;p<echo-2;p++)
    insert(fifo,0,echo);
    while(fread(&sample,2,1,file_in))
    read_out(&temp,fifo,echo);
    temp = temp/3 + sample/2;
    insert(fifo,temp,echo);
    fwrite(&temp,2,1,file_out);
    fclose(file_out);
    fclose(file_in);
    delete fifo;
    return 0;
    void insert(short int * tablica,short int element,int value)
    tablica[write%value]=element;
    write++;
    void read_out(short int * liczba,short int * tablica,int value)
    (*liczba)=tablica[read%value];
    read++;
    }as You see above it's very simple, and I wrote it ages ago, and now I need to prepare a presentation for a JUG meeting, and it's gonna be about all java support for different kinds of sound. That's why I wanna write application to manipulate some sort of sound files ( in this case a .wav file).
    My problem is that when I repeat this code in Java it works differently. first problem, is that I read samples form wav using FileInputStreamReader, and it reads either bytes or ints , and I need to read shorts, cause it's 16bit wav file. So I'm reading via FileInputStreamReader every 2 bytes, and trying to convert it to short using bit shifts, but it never works. Does anyone knows how to read stream to short type, or how to convert bytes[2] to short safely? Thanks in advance.

    I was having a very similar problem converting a byte array to a double array. Please see this thread:
    http://forums.sun.com/thread.jspa?threadID=5438070&tstart=0
    The method suggested by captfoss in that thread and in this thread should work, but it doesn't seem to work correctly. Instead, I had to handle each bit on an individual basis to get the correct result, like this:
                                    int d = 0;
                                    for (int j = 0; j < 8; j++) {
                                        if (((data[2*i] >>> j) & 1) == 1) {
                                            d += (int) Math.pow(2, j);
                                    for (int j = 0; j < 7; j++) {
                                        if (((data[2*i+1] >>> j) & 1) == 1) {
                                            d += (int) Math.pow(2, j+8);
                                    if (((data[2*i+1] >>> 7) & 1) == 1) {
                                        d -= Math.pow(2, 15);
                                    wave.get(lastD) = d;
    wave is a double array, so it casts d to a double in the last line.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

  • How to create RSAPublicKeySpec from byte[]

    Hi,
    another question: i've the public key encoded in ascii format on disk. How can i create the RSAPublicKeySpec from that byte[] array? i don't have the modulus and exponent...
    thanks
    Luca

    Take a look at java.security.KeyFactory.generatePublic(KeySpec) and java.security.spec.X509EncodedKeySpec.
    Grant

  • How can I get String from Bytes

    I want to get String from array of bytes but i have some trouble from byte that it's lager more than 128. How can I do ???
    Please hepl me. Thanks very much.

    This program is only to show you what the relationships are between unsigned byte, signed byte, character, and binary values. Because of the constraints that Java has, the program code is not especially clean. Run the program and see if it helps. As has been said, the character output is dependent on the encoding in use.
    Here is a sample of some of its output:
    Unsigned byte= 189 Signed byte= -67 Character= � Binary= 10111101
    Unsigned byte= 190 Signed byte= -66 Character= � Binary= 10111110
    Unsigned byte= 191 Signed byte= -65 Character= � Binary= 10111111
    Unsigned byte= 192 Signed byte= -64 Character= � Binary= 11000000
    Unsigned byte= 244 Signed byte= -12 Character= � Binary= 11110100
    Unsigned byte= 245 Signed byte= -11 Character= � Binary= 11110101
    Unsigned byte= 246 Signed byte= -10 Character= � Binary= 11110110
    public class ATest {
        public static void main(String[] args) {
            int in;
            byte by;
            String bin;
            char chr;
            for(in=0; in<256; in++) {
                // create a byte whose binary value is equal to the;
                // integer loop counter;
                by = (byte)in;
                // mask off sign extension [that I don't agree with!] and;
                // cast the resultant 8 bits to a char;
                chr = (char)(by & 0x00ff);
                // since there's no Byte.toInteger, must cast to int to get;
                // binary string and then delete unwanted portion of string;
                if(in<128) {
                    bin = Integer.toBinaryString((int)by);
                } else {
                    bin = Integer.toBinaryString((int)by).substring(24);
                // print everything;
                System.out.println(
                    "Unsigned byte= "+in+
                    " Signed byte= "+by+
                    " Character= "+chr+
                    " Binary= "+bin);
    }

  • How could I choose some bytes from HEX string and then convert it to a decimal value?

    Hi I am working with an OMRON E5EN temperature controller using VISA serial to get data, I send the Read from Variable Area command and get this string  in hexa 0230 3130 3030 3030 3130 3130 3030 3030 3030 3030 3041 3203 71 or .01000001010000000000A2.q in ASCII this string means:
    02 STX
    3031 3030 Node and subadress
    3030 End Code Normal Completion
    3031 3031 Command Read from Variable Area
    3030 3030 respt code Normal completion
    3030 3030 3030 4132 Hexadecimal A2 = 162  (this is the temperature data that I want to show in decimal)
    03 ETX
    71 Block Check Character
    I want to choose the eight bytes for the temperature data and convert it to a decimal number. I have seen the examples to convert a Hexa string to decimal but I do not know how to choose the specifics bytes that I need.
    I have look for a driver but i didn´t find any. I am a beginner so please include especific topics for me to study in your answer.
    Thanks
    Carlos Fuentes Silva Queretaro Mexico 

    If the response always has the temperature starting with byte 15 and is always 8 bytes in length, you can use the String Subset function to get those bytes out of the string.  Then use Hex String to Number to convert to a decimal number.
    Well someone already beat me to the solution:
    Message Edited by tbob on 01-04-2008 04:42 PM
    - tbob
    Inventor of the WORM Global
    Attachments:
    HexStr2Decimal.png ‏7 KB

  • How can we read some bytes from every line of the file

    How can we read some bytes from the every line of the file moving on to the next line
    without using the read line

    Actualiy readLine() takes more execution time
    for reading a part of line if we can do so without
    readLine() we can save some time...Well, if you knew, beforehand, the length of each line, you could use RandomAccessFile and its seek method, but, since you don't, you would have to read the rest of the line character-by-character, checking to see if it is a newline, in order to place the "cursor" at the beginning of the next line in order to read the next few characters you want.
    So, as you can see, you will need to read the entire line anyway (and if you do it yourself you also have to do the checking yourself considering all three possible end-of-line sequences), so you just as well use readLine().
    Some people may suggest Scanner and it's nextLine() method, but that also needs to read the rest of line (as evidenced by the fact that it returns it), so that is no different than the readLine() (or read it yourself) solution.

  • XMLEncoder - how to stop it from using NaN for int's

    I am trying to invoke a webservice. I used the Flex Builder 3
    service code generator. I have an object "Person" which has three
    fields: {id:int, firstName:String, lastName:String}
    I have a case where I invoke a method on a webservice that
    takes a person object. the person object in this case should only
    have a first and last name defined (no id, yet). I stepped through
    the flex source code to see what happens and basically when it
    encodes the Person object it gets to the "id" field whose value is
    NaN (b/c I never set it). The encoder eventually just decides that
    (NaN >= integer.min value) and passes it along so it gets into
    my SOAP message as <id>NaN</id>. This causes problems
    at the web service (java) side b/c it doesn't know how to
    unmarshall "NaN".
    So...any suggestions on how to prevent it from sending
    <id>NaN</id>. maybe even just <id /> would be
    ok.

    Moving the iOS device backup location
    Open a command prompt by hitting the start button and typing CMD<Enter> in the search box that opens up, or with Start > Run on older Windows.
    To move the current backup folder from C: to D: (for example) type in this command and press <Enter>
    Move "C:\Users\<User>\AppData\Local\Apple Computer\MobileSync\Backup" "D:\Backup"
    Where <User> is your Windows user name.
    To make iTunes look for the data in the new location type in this command and press <Enter>
    MkLink /J "C:\Users\<User>\AppData\Local\Apple Computer\MobileSync\Backup" "D:\Backup"
    If your preferred drive has a different letter or you already have a folder called "Backup" then edit "D:\Backup" accordingly in both commands.
    If you have Windows XP then you'll need a third-party tool such as Junction to link the two locations together instead of the MkLink command. The source folder is C:\Documents and Settings\<User>\Application Data\Apple Computer\MobileSync\Backup
    I'm pretty sure the same technique will work with the iPod software download folder, although it is worth noting that it does not work inside the iTunes Media folder. At last time of testing if you attempt to redirect sections of the media folder and iTunes writes to a redirected location it will erase the link and replace it with a regular folder.
    tt2

  • How can I make byte[] to int?(the byte order is diff for intel and sparc))

    i do a net program with java, it send message
    from sun to pc with socket, i want to change
    byte[] to int and int to byte[], the byte order is
    diff from sparc and intel, and i can not use
    the ByteArrayStream, is there any way?
    thanks.

    you can connect the headset to something like this
    http://www.ebay.com/itm/NEW-MaelineA-3-5mm-Female-to-2-Male-Gold-Plated-Headphon e-Mic-Audio-Y-Splitter-/381100440348
    and then connect the mic to the input and the headset to the headset port

  • How to send the image bytes(which is taken from webcam) from flex(4.6 version) to dotnet

    In my project we are using adobe flash builder 4.6 as a client-side scripting,visual studio as a mediator(for connecting the oracle database).In this, in flex 4.6 we are capturing images from webcam that's working fine, after capturing the image we need to save this captured image in oracle database so in order to save we need to pass this image from flex to dot-net(visual studio) so i need a help on how to approach to done this(passing the image from flex to dot-net) if any one knows please help me i will be very thankful to them

    finally i got the solution fot this,i tried using yhis link it work's for me
    http://stackoverflow.com/questions/5702239/how-to-pass-image-from-a-flex-application-to-a- asp-net-c-sharp-web-service

  • How to join  fields from different internal tables and display into one int

    hai i have one doubt...
    how to join  fields from different internal tables and display into one internal table..
    if anybody know the ans for this qus tell me......

    hii
    you can read data as per condition and then can join in one internal table using READ and APPEND statement..refer to following code.
    SELECT bwkey                         " Valuation Area
             bukrs                         " Company Code
        FROM t001k
        INTO TABLE i_t001k
       WHERE bukrs IN s_bukrs.
      IF sy-subrc EQ 0.
        SELECT bwkey                       " Valuation Area
               werks                       " Plant
          FROM t001w
          INTO TABLE i_t001w
           FOR ALL ENTRIES IN i_t001k
         WHERE bwkey = i_t001k-bwkey
           AND werks IN s_werks.
        IF sy-subrc EQ 0.
          LOOP AT i_output INTO wa_output.
            READ TABLE i_t001w INTO wa_t001w WITH KEY werks = wa_output-werks.
            READ TABLE i_t001k INTO wa_t001k WITH KEY bwkey = wa_t001w-bwkey.
            wa_output-bukrs = wa_t001k-bukrs.
            MODIFY i_output FROM wa_output.
            CLEAR wa_output.
          ENDLOOP.                         " LOOP AT i_output
        ENDIF.                             " IF sy-subrc EQ 0
    regards
    twinkal

  • How to extract text from a PDF file?

    Hello Suners,
    i need to know how to extract text from a pdf file?
    does anyone know what is the character encoding in pdf file, when i use an input stream to read the file it gives encrypted characters not the original text in the file.
    is there any procedures i should do while reading a pdf file,
    File f=new File("D:/File.pdf");
                   FileReader fr=new FileReader(f);
                   BufferedReader br=new BufferedReader(fr);
                   String s=br.readLine();any help will be deeply appreciated.

    jverd wrote:
    First, you set i once, and then loop without ever changing it. So your loop body will execute either 0 times or infinitely many times, writing the same byte every time. Actually, maybe it'll execute once and then throw an ArrayIndexOutOfBoundsException. That's basic java looping, and you're going to need a firm grip on that before you try to do anything as advanced as PDF reading. the case.oops you are absolutely right that was a silly mistake to forget that,
    Second, what do the docs for getPageContent say? Do they say that it simply gives you the text on the page as if the thing were a simple text doc? I'd be surprised if that's the case.getPageContent return array of bytes so the question will be:
    how to get text from this array? i was thinking of :
        private void jButton1_actionPerformed(ActionEvent e) {
            PdfReader read;
            StringBuffer buff=new StringBuffer();
            try {
                read = new PdfReader("d:/getjobid2727.pdf");
                read.getMetaData();
                byte[] data=read.getPageContent(1);
                int i=0;
                while(i>-1){ 
                    buff.append(data);
    i++;
    String str=buff.toString();
    FileOutputStream fos = new FileOutputStream("D:/test.txt");
    Writer out = new OutputStreamWriter(fos, "UTF8");
    out.write(str);
    out.close();
    read.close();
    } catch (Exception f) {
    f.printStackTrace();
    "D:/test.txt"  hasn't been created!! when i ran the program,
    is my steps right?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • How to tranfer file from between two client?

    Hi, all:
    I'd like to tranfer file from client A to client B. Basically, I will treat one of them is client and one of them is server, then create a server socket/socket connection, then they can conmmunicate. I know how to talk between them. However, I don't know how to trasfer file from client to server, or from server to client in the same class. I mean not two class: Server socket and client socket.
    Consider the following case:
    There is a function, just like MSN file transfer: transfer file from localhost to "10.4.155.8". How can I transfer file from localhost to "10.4.155.8"?
    Help please.
    --Paul                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    Hi, man:
    Thanks.
    I agree with you at most.
    I am doing my practise project: the other MSN Messenger and more, I will include file encryption and file decryption, etc.
    My point is one connection will make center server too heavy. Then I have to adapt your first means:
    promote either Client A or Client B become server, leave the other guy still being client, because I know their IP address. This will free the server a lot.
    BTW, I finish my code pretty much, say 70%. However, I felt tired for coding. I have my full time job in software development at daytime. I am looking one or two guy to share this project. My point is to improve the performance of the this Messenger. I feel my code maybe work fine with hundred of con-current user, maybe not, or maybe more, not sure. My email: [email protected]. (I put my name means I am searious).
    Could anyone feel he/she is good at Messenger, please email me, then we can share my code with you.
    Code sample for file transfer:
    //For Client side
    import java.io.*;
    import java.net.*;
    class Client
    public static void main(String args[]) throws Exception
    String sentence;
    String host = "localhost";
    int SERVER_LISTEN_PORT = 5432;
    BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
    Socket clientSocket = null;
    DataOutputStream outToServer = null;
    BufferedInputStream inFromServer = null;
    try
    clientSocket = new Socket(host, SERVER_LISTEN_PORT);
    outToServer = new DataOutputStream(clientSocket.getOutputStream());
    inFromServer = new BufferedInputStream(clientSocket.getInputStream());
    }catch(UnknownHostException e)
    System.err.println("Don't know about host: "+host);
    }catch(IOException e)
    System.err.println("Couldn't get I/O for the connection to: "+host);
    sentence = inFromUser.readLine();
    outToServer.writeBytes(sentence + '\n');
    FileOutputStream fos = new FileOutputStream("c://test.doc");
    int totalDataRead;
    int totalSizeWritten = 0;
    int DATA_SIZE = 20480;
    byte[] inData = new byte[DATA_SIZE];
    System.out.println("Begin");
    while ((totalDataRead = inFromServer.read(inData, 0, inData.length)) >= 0)
    fos.write(inData, 0, totalDataRead);
    totalSizeWritten = totalSizeWritten + totalDataRead;
    System.out.println(totalSizeWritten);
    System.out.println("Done");
    fos.close();
    clientSocket.close();
    //For Client side
    import java.io.*;
    import java.net.*;
    class Server
    public static void main(String args[]) throws Exception
    int SERVER_LISTEN_PORT = 5432;
    String clientSentence;
    ServerSocket welcomeSocket = null;
    try
    welcomeSocket = new ServerSocket(SERVER_LISTEN_PORT);
    }catch(IOException ioe)
    System.out.println("Could not listen on port: " + SERVER_LISTEN_PORT);
    System.exit(1);
    while(true)
    Socket connectionSocket = null;
    try
    connectionSocket = welcomeSocket.accept();
    }catch(IOException ioe)
    System.err.println("Accept failed.");
    System.exit(1);
    BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
    BufferedOutputStream outToClient = new BufferedOutputStream(connectionSocket.getOutputStream());
    System.out.println(inFromClient.readLine());
    int data;
    int totalSizeTransferred = 0;
    int totalSizeRead;
    int PACKET_SIZE = 20480;
    byte[] packet = new byte[PACKET_SIZE];
    System.out.println("reading file...");
    FileInputStream fis = new FileInputStream("c://JVM_Profiling_Report.doc");
    while ((totalSizeRead = fis.read(packet, 0, packet.length)) >= 0)
    outToClient.write(packet, 0, totalSizeRead);
    totalSizeTransferred = totalSizeTransferred + totalSizeRead;
    System.out.println(totalSizeTransferred);
    System.out.println("done reading file...");
    outToClient.close();
    fis.close();
    My question, any good idea for creating progress bar?
    Thanks.

  • How to move files from one folder to another folder in webdynpro java for sap portal

    Dear Experts,
    I wan to move files from one folder to another folder in SAP portal 7.3 programmatically in webdynpro java.
    My requirement is in my portal 1000 transport packages is their. Now i want to move 1 to 200 TP's into Archive folder.
    Can you please help me how to do in through portal or wd java ...
    Regards
    Chakri

    Hello,
    Do you know what the difference between copying a file this way :
    ** Fast & simple file copy. */
    public static void copy(File source, File dest) throws IOException {
    FileChannel in = null, out = null;
    try {         
    in = new FileInputStream(source).getChannel();
    out = new FileOutputStream(dest).getChannel();
    long size = in.size();
    MappedByteBuffer buf = in.map(FileChannel.MapMode.READ_ONLY, 0, size);
    out.write(buf);
    } finally {
    if (in != null) in.close();
    if (out != null) out.close();
    ================SECOND WAY============
    AND THIS WAY:
    // Move file (src) to File/directory dest.
    public static synchronized void move(File src, File dest) throws FileNotFoundException, IOException {
    copy(src, dest);
    src.delete();
    // Copy file (src) to File/directory dest.
    public static synchronized void copy(File src, File dest) throws IOException {
    InputStream in = new FileInputStream(src);
    OutputStream out = new FileOutputStream(dest);
    // Transfer bytes from in to out
    byte[] buf = new byte[1024];
    int len;
    while ((len = in.read(buf)) > 0) {
    out.write(buf, 0, len);
    in.close();
    out.close();
    And which is better? I read up on what each kind of does but still a bit unclear as to when it is good to use which.
    Thanks in advance,
    JavaGirl

  • How to track no of bytes transferred

    Hi there,
    how to track no of bytes transferred
    while downloading a file using java servlets.
    please note that i am not writing any client side application like applet...
    Hence I want to track no of bytes transffered to client end from my server (using servlets)
    Please kindly help me out as soon as possible.
    awaiting the solution immediately.
    thanks,
    venkat

    //the following is the code what i have written in my servlet.
    res.setContentType(MIME); // I hava parameterised the MIME tag
    OutputStream out=res.getOutputStream();
    int counter=0;
    File f1 = new File("c:/x.pdf");
    //int k=(int)f1.length();
    fis = new FileInputStream(f1);
    byte[] buffer=new byte[fis.available()];
    fis.read(buffer);
    for(i=0; i<buffer.length; i++)
    try
    counter=i+1; //getting the number of bytes got transferred
    out.write(buffer,i,1); //write to client's directory
    catch(IOException ex)
    System.out.println("exception while download="+ex.getMessage());
    downloaded=true;
    if(counter!=buffer.length)
    download_error="Not Downloaded";
    download=false;
    //while executing the above servlet, the servlet prompts for a save as dialog (without file extension, please note I have specified the MIME tag also).
    Now the client is entering the file and clicking save
    In between he cancels and file is not downloaded to the client's directory.
    Now the counter length should not match with the buffer.length, but it is matching exactly and stating that the file has been downloaded properly.
    I hope you would have understood my problem.
    Also note that I dont have any client side application to monitor the download.
    Please let me know how to solve the problem as soon as possible
    expecting your reply at the earliest thanks.

  • How to download file from application server

    Hi Experts,
                  I developed report and execute in background mode. for this i used Open dataset transfer and close dataset . i got the requried output . But in this case user want downloaded file on presentation server so can anyone tell me How to download file from application server?
    i know it is possible through Tcode CG3Y. but i want code in program.

    This code will download a file to your Client package by package, so it will also work for huge files.
    *& Report  ZBI_DOWNLOAD_APPSERVER_FILE
    REPORT  zbi_download_appserver_file.
    PARAMETERS: lv_as_fn TYPE sapb-sappfad
    DEFAULT '/usr/sap/WBP/DVEBMGS00/work/ZBSPL_R01.CSV'.
    PARAMETERS: lv_cl_fn TYPE string
    DEFAULT 'C:\Users\atsvioli\Desktop\Budget Backups\ZBSPL_R01.CSV'.
    START-OF-SELECTION.
      CONSTANTS blocksize TYPE i VALUE 524287.
      CONSTANTS packagesize TYPE i VALUE 8.
      TYPES ty_datablock(blocksize) TYPE x.
      DATA lv_fil TYPE epsf-epsfilnam.
      DATA lv_dir TYPE epsf-epsdirnam.
      DATA ls_data TYPE ty_datablock.
      DATA lt_data TYPE STANDARD TABLE OF ty_datablock.
      DATA lv_block_len TYPE i.
      DATA lv_package_len TYPE i.
      DATA lv_subrc TYPE sy-subrc.
      DATA lv_msgv1 LIKE sy-msgv1.
      DATA lv_processed_so_far TYPE p.
      DATA lv_append TYPE c.
      DATA lv_status TYPE string.
      DATA lv_filesize TYPE p.
      DATA lv_percent TYPE i.
      "Determine size
      SPLIT lv_as_fn AT '/' INTO lv_dir lv_fil.
      CALL FUNCTION 'EPS_GET_FILE_ATTRIBUTES'
        EXPORTING
          file_name      = lv_fil
          dir_name       = lv_dir
        IMPORTING
          file_size_long = lv_filesize.
      "Open the file on application server
      OPEN DATASET lv_as_fn FOR INPUT IN BINARY MODE MESSAGE lv_msgv1.
      IF sy-subrc <> 0.
        MESSAGE e048(cms) WITH lv_as_fn lv_msgv1 RAISING file_read_error.
        EXIT.
      ENDIF.
      lv_processed_so_far = 0.
      DO.
        REFRESH lt_data.
        lv_package_len = 0.
        DO packagesize TIMES.
          CLEAR ls_data.
          CLEAR lv_block_len.
          READ DATASET lv_as_fn INTO ls_data MAXIMUM LENGTH blocksize LENGTH lv_block_len.
          lv_subrc = sy-subrc.
          IF lv_block_len > 0.
            lv_package_len = lv_package_len + lv_block_len.
            APPEND ls_data TO lt_data.
          ENDIF.
          "End of file
          IF lv_subrc <> 0.
            EXIT.
          ENDIF.
        ENDDO.
        IF lv_package_len > 0.
          "Put file to client
          IF lv_processed_so_far = 0.
            lv_append = ' '.
          ELSE.
            lv_append = 'X'.
          ENDIF.
          CALL FUNCTION 'GUI_DOWNLOAD'
            EXPORTING
              bin_filesize         = lv_package_len
              filename             = lv_cl_fn
              filetype             = 'BIN'
              append               = lv_append
              show_transfer_status = abap_false
            TABLES
              data_tab             = lt_data.
          lv_processed_so_far = lv_processed_so_far + lv_package_len.
          "Status display
          lv_percent = lv_processed_so_far * 100 / lv_filesize.
          lv_status = |{ lv_percent }% - { lv_processed_so_far } bytes downloaded of { lv_filesize }|.
          CALL FUNCTION 'SAPGUI_PROGRESS_INDICATOR'
            EXPORTING          "percentage = lv_percent - will make it fash
              text = lv_status.
        ENDIF.
        "End of file
        IF lv_subrc <> 0.
          EXIT.
        ENDIF.
      ENDDO.
      "Close the file on application server
      CLOSE DATASET lv_as_fn.

Maybe you are looking for

  • Mac mini (Late 2012): Dual- or Quad-Core?

    I'm upgrading from a MacBook (2006) and - as a frequent iPad user - am thinking of just getting a Mac mini. I'm not sure though as wether to get the i5 dual-core or i7 quad-core version. What I'll be using it for (none of these on a professional leve

  • Photo album in iPhoto

    How do you like iPhoto as an organizing tool for your photos?

  • How to change Stored Procedure Parameters to a value in a formula?

    My Client is using Crystal 8.5 on MSSQL 2005.  The crystal report is called from vb6 application, the client does not have access to the vb6 source code (they are upgrading vb.net), therefore I can only work in the crystal report. The vb6 code update

  • Sun ONE Studio 5 evaluation. JDBC RowSet question.

    I am accessing a MYSQL database using form wizard. I am also using the DataNavaigator. When I use RowSet type: NB CachedRowSet, I can bring in and scroll through existing data, add, change, and delete rows with no problem. When I use NB JDBC RowSet,

  • DrLazaroJamF It can be done... challange complete....

    Here ya go without a SpringLayout. However I still don't get GridBagLayout.      private static void addComponentsToPane(Container pane)           JPanel northPanel  = new JPanel();           northPanel.setLayout(new GridLayout(4, 2) );           //C