logo
down
shadow

download only first N bytes from file on web JAVA Android


download only first N bytes from file on web JAVA Android

By : user2954714
Date : November 22 2020, 10:31 AM
I wish this helpful for you I want download only first 3 bytes of file from web, but can't do that.
code :
connection.setRequestProperty("Range", "bytes="+0+"-"+2);
        connection.connect();

        BufferedReader r = new BufferedReader(new InputStreamReader(connection.getInputStream()));

        StringBuilder total = new StringBuilder();
        String line;
        line = r.readLine();
        Log.i(LOG_TAG, line);


Share : facebook icon twitter icon
Android Java - How to download zip file from URL?

Android Java - How to download zip file from URL?


By : MK Shatnawi
Date : March 29 2020, 07:55 AM
I wish this help you Hey Im making a new project which requires you to download some files from my Dropbox. I added a new class called DownloadFile which has the code to download a file. For some reason the app crashes when I click download. . , You are declaring DownloadFile object but not initializing it.
code :
private DownloadFile df;
df.Download(); // Throws NPE
private DownloadFile df = new DownloadFile();
df.Download();
Android java. From a service, i want to download a file

Android java. From a service, i want to download a file


By : Om Keshri
Date : March 29 2020, 07:55 AM
I hope this helps you . You should not do network related heavy operation from main thread. You can use AsyncTask/Thread to call api.
You can also use networking library like volley, retrofit etc.
Firebase file download on Android shows 0 bytes

Firebase file download on Android shows 0 bytes


By : Suman M R
Date : March 29 2020, 07:55 AM
This might help you Edit: Nevermind, I figured it out. I didn't supply enough code. I had both a copy file and create database function happen outside of the OnSuccess listener within the method that posted the OnSuccess listener. Those extra functions acted on the temp file. One of these must've disrupted the download process. I put them inside of the OnSuccess listener and it worked perfectly.
Java, bytes read by TargetDataLine, Bad code saving its bytes to file

Java, bytes read by TargetDataLine, Bad code saving its bytes to file


By : user3370982
Date : March 29 2020, 07:55 AM
this one helps. Reviewing in detail using a binary comparator...
Check the line 088
code :
boolean endianness = false;
AudioFormat audioformat = new AudioFormat(sampleRate, 8 * numBytesPerSample,
    numChannels, true, endianness);
public class CatchingSoundBytes {

  public static void main(String[] args) {

    try {
      new CatchingSoundBytes().executor();
    } catch (LineUnavailableException ex) {
      ex.printStackTrace();
    }
  }

  public void executor() throws LineUnavailableException {
    int numChannels = 1;
    int numBytesPerSample = 2;
    int sampleRate = 8192;
    boolean endianness = false;
    AudioFormat audioformat = new AudioFormat(sampleRate, 8 * numBytesPerSample, numChannels, true, endianness);
    DataLine.Info dataLineInfo = new DataLine.Info(TargetDataLine.class, audioformat);
    TargetDataLine targetDataLine = (TargetDataLine) AudioSystem.getLine(dataLineInfo);
    try {
      targetDataLine.open(audioformat);
      targetDataLine.start();
    } catch (LineUnavailableException ex) {
      System.out.println("ex:" + ex.getMessage());
    }

    int bufferSize = (int) Math.pow(2.0, 11);
    final PipedOutputStream srcSavePOStream = new PipedOutputStream();
    final PipedInputStream snkSavePIStream = new PipedInputStream(bufferSize);
    try {
      snkSavePIStream.connect(srcSavePOStream);
    } catch (IOException ex) {
      System.out.println("ex:" + ex.getMessage());
    }

    String dateFilename = (endianness ? "Big" : "Lit") + new SimpleDateFormat("yyyyMMdd-HHmm").format(new Date());

    // INI Save File
    new Thread(() -> {
      AudioInputStream aisRecording = new AudioInputStream((InputStream) snkSavePIStream, audioformat, AudioSystem.NOT_SPECIFIED);
      File fileRecordedWav = new File("AIS_" + dateFilename + ".wav");
      System.out.println("fileRecordedWav:" + fileRecordedWav.getAbsolutePath());
      try {
        AudioSystem.write(aisRecording, AudioFileFormat.Type.WAVE, fileRecordedWav);
      } catch (IOException ex) {
        System.out.println("Save File -> ex:" + ex.getMessage());
      }
    }).start();
    // END Save File

    BlockingQueue<BytesSound> blockingQueue = new LinkedBlockingQueue<>();
    Stopper stopper = new Stopper();
    stopper.setRunning(true);

    // INI Capture Sound
    new Thread(() -> {
      try {
        long index = 0;
        byte[] buffer = new byte[bufferSize];
        while (stopper.isRunning()) {
          try {
            int count = targetDataLine.read(buffer, 0, bufferSize);
            if (count > 0) {
              byte[] output = new byte[count];
              System.arraycopy(buffer, 0, output, 0, count);
              srcSavePOStream.write(output); // Send to Save Using AudioSystem.write
              blockingQueue.put(new BytesSound(endiannessReorderedBytes(output, audioformat), index)); // Send to Save Using RandomAccessFile
            }
          } catch (Exception ex) {
            System.out.println("Capture Sound -> ex:" + ex.getMessage());
          }
          index++;
          if (index > 1) {
            break;
          }
        }
        targetDataLine.stop();
      } catch (Exception ex) {
        System.out.println("Capture Sound -> ex:" + ex.getMessage());
      } finally {
        try {
          targetDataLine.close();
        } catch (SecurityException e) {
        }
      }
    }).start();
    // END Capture Sound

    // INI Save RandomAccessFile File
    new Thread(() -> {
      String filename = "RAF_" + dateFilename + ".wav";
      System.out.println("raf:" + filename);
      long index = 0;
      while (stopper.isRunning()) {
        try {
          BytesSound bytesSound = blockingQueue.take();
          if (bytesSound instanceof Kill) {
            break;
          }
          //REALLY I don't need to save bytes in this stage,
          //only in order to compare with payload of method using AudioSystem.write
          // I need the bytes and position for processing

          RandomAccessFile raf = new RandomAccessFile(filename, "rw");
          addSample(raf, bytesSound);
          raf.close();
        } catch (Exception ex) {
          System.out.println("Save RandomAccessFile File -> ex:" + ex.getMessage());
        }
        index++;
        if (index > 1) {
          break;
        }
      }
      System.out.println("Expected Size:" + index * bufferSize);
    }
    ).start();
    // END Save RandomAccessFile File

    new Timer(true).schedule(new TimerTask() {
      @Override
      public void run() {
        stopper.setRunning(false);
      }
    }, 4000L);
  }

  private byte[] endiannessReorderedBytes(byte[] incomingBytes, AudioFormat audioformat) {
    if (!(incomingBytes != null && audioformat != null)) {
      throw new IllegalArgumentException("Some arguments are null.");
    }
    byte[] outgoingBytes = new byte[incomingBytes.length];
    if (audioformat.getSampleSizeInBits() == 16) {
      if (incomingBytes.length % 2 != 0) {
        throw new IllegalArgumentException("The size of the byte array does not match the audio format.");
      }
      int count = incomingBytes.length / 2;
      if (audioformat.isBigEndian()) {
        for (int i = 0; i < count; i++) {
          outgoingBytes[i * 2] = incomingBytes[i * 2 + 1];
          outgoingBytes[i * 2 + 1] = incomingBytes[i * 2];
        }
      } else {
        System.arraycopy(incomingBytes, 0, outgoingBytes, 0, incomingBytes.length);
      }
    } else {
      if (audioformat.getEncoding() == Encoding.PCM_SIGNED) {
        for (int i = 0; i < incomingBytes.length; i++) {
          outgoingBytes[i] = (byte) (0x80 ^ incomingBytes[i]);
        }
      } else {
        System.arraycopy(incomingBytes, 0, outgoingBytes, 0, incomingBytes.length);
      }
    }
    return outgoingBytes;
  }


  private void addSample(RandomAccessFile raf, BytesSound bytesSound) {
    try {
      raf.seek(44 /*Header Length*/ + bytesSound.getIndex() * bytesSound.getChunk().length);
      raf.write(bytesSound.getChunk());
    } catch (IOException ex) {
      System.out.println("ex:" + ex.getMessage());
    }
  }

  private class BytesSound {

    private final byte[] chunk;
    private final long index;

    public BytesSound(byte[] chunk, long index) {
      this.chunk = chunk;
      this.index = index;
    }

    public byte[] getChunk() {
      return chunk;
    }

    public long getIndex() {
      return index;
    }

  }

  private class Kill extends BytesSound {

    public Kill(byte[] chunk, long index) {
      super(chunk, index);
    }
  }

  private class Stopper {

    private boolean running;

    public boolean isRunning() {
      return running;
    }

    public void setRunning(boolean running) {
      this.running = running;
    }

  }
}
Using Java HttpUrlConnection to download a PDF file,buffer set to 1024 bytes -- Wrong,but 8 is ok

Using Java HttpUrlConnection to download a PDF file,buffer set to 1024 bytes -- Wrong,but 8 is ok


By : That Who
Date : March 29 2020, 07:55 AM
it should still fix some issue You're unconditionally writing out the whole of the buffer on each iteration. You should only write out as many bytes as you've just read:
Related Posts Related Posts :
  • Stream corrupted exception - invalid code type AC [java]
  • Routing Sysout values to JTextArea
  • GWT RPC serialization for Dynamic Host Page
  • Best Approch of Returning Value from 'getter' Method
  • Understanding xml schemalocation
  • Checking if a PDF is PDF/A 1-a format or not using PDFBOX in java
  • Difference Between Variable and Identifier
  • How to compute two aggregate functions with Java streams?
  • Parse the value of the json to baseadapter in android?
  • JavaFX animation on raspberry pi
  • Solve "unchecked warning" in Java avoiding @suppressWarnings
  • How to specify a new name for a file while moving it to another directory in Java?
  • Popup window not showing up with spinner item selection?
  • how to iterate through json objects in java
  • Caused by: java.lang.NoClassDefFoundError: org/springframework/aop/framework/AbstractAdvisingBeanPostProcessor
  • Getting NoClassDefFoundError while running PMD task from Gradle
  • Matlab drag and drop file from windows explorer to figure (gui)
  • How does scala's actor model make use of C threads and native system threads?
  • Store java.util.Date as key in a Map based on reference equality instead of "value" equality
  • Error when logging into FTP from AsyncTask class using org.apache.commons.net.ftp.FTPClient
  • creating unique index in mongoDB
  • hibernate Query to find record based on substring
  • How many strings are in jvm string pool intern
  • Unable to initialize native-platform. on Jenkins
  • How to create a list of dummy files in Java?
  • Docker: Which approach is better? WAR embedded in image or base image + war?
  • java.lang.InternalError: CallerSensitive annotation expected at frame 1
  • How to write a method to read JSON files of different structures and return different POJO objects in Java?
  • Reference to Classes in Java
  • Unable to call function via companion object
  • REST: convert XML content passed with POST to a java object, attribute inside the element
  • Device not receive message from GCM
  • How to increase Openfire concurrent connection limit?
  • Android send custom parameter on AsyncTask
  • GWT - Get dom element's value from another page
  • How can i initialize an array in Java?
  • Is it possible to increase a java process's(when is running) size?
  • Getting Node Address instead of Value in Binary Search Tree
  • PdfByteContent not adding in iText pdf
  • Spring JpaRepository: delete() with subsequent save() in the same transaction
  • producer-consumer using arraydeque working only in breakpoint
  • Adding a JPanel to another JPanel
  • Comparison with operator ==, how does it work?
  • Error buildling with maven for openshift
  • What is the java equivilant to MySQL's smallint
  • proxy trouble on eclipse with https
  • Spring-Jdbc Template and Prepared statement
  • Mule - exception in Outbound endpoint Message payload is of type: byte[]
  • Modify package names for java classes generated from wsdl
  • How to download multiple images and have one progressBar using AsynTask (Android)
  • Implementing Service Provider, IdP and user in java with SAML (POC)
  • Why does my scanner repeat?
  • Can I forget ResultSetFuture in Cassandra java driver without facing memory leak?
  • XML to JAXB binding having nested elements?
  • Java: ToString() prints the same hashcode each time
  • Why am I getting a thread exception in my graphics program?
  • Can we read 4th byte from hexadecimal value?
  • How to create watermark in image just like Google maps watermarks
  • how come Thread class called inside another class?
  • AssertionError: Unexpected schema version 0: Unexpected schema version 0
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org