This question already has answers here:
Java multiple file transfer over socket
(3 answers)
Closed 4 years ago.
I'm trying to send multiple files over java sockets. After successfully receiving first file, it throws EOFexception. I am unable to figure out what's going wrong. (All files are successfully sent from sender's side)
Sender's code :
sendToServer = new Socket(receiver,port);
DataOutputStream out = new DataOutputStream(sendToServer.getOutputStream());
for(File f: file_to_send){
sendMessage = f.getName() + "\n"+ f.length() + "\n";
out.writeUTF(sendMessage);
FileInputStream requestedfile = new FileInputStream(f.getPath());
System.out.println("file path: "+f.getPath());
int count;
byte[] buffer = new byte[8192];
while ((count = requestedfile.read(buffer)) > 0)
{
out.write(buffer, 0, count);
}
System.out.println("File transfer completed!! voila! :)");
requestedfile.close();
}
out.close();
sendToServer.close();
Receiver's code :
System.out.println("File Count : " + fileCount);
for (int count =0; count<fileCount; count++){
String fileName = dis.readUTF();
int length = Integer.parseInt(fileName.split("\n")[1]);
fileName = fileName.split("\n")[0];
System.out.println("File Name : " + fileName);
System.out.println("Length : " + length);
System.out.println("File Data : ");
FileOutputStream fos = new FileOutputStream(new File(fileName));
int c;
byte[] buffer = new byte[8192];
while ((c = dis.read(buffer)) > 0)
{
fos.write(buffer, 0, c);
fos.flush();
}
fos.close();
System.out.println("\nFile received successfully!!! voila !! :)");
}
And the output is like this :
Files Count : 2
File Name : Belly Dance.3gp
Length : 15969978
File Data :
File received successfully!!! voila !! :)
java.io.EOFException
at java.base/java.io.DataInputStream.readUnsignedShort(DataInputStream.java:345)
at java.base/java.io.DataInputStream.readUTF(DataInputStream.java:594)
at java.base/java.io.DataInputStream.readUTF(DataInputStream.java:569)
at App.java.DiscoveryClient.HandleInputMessage(DiscoveryClient.java:130)
at App.java.DiscoveryClient.run(DiscoveryClient.java:44)
at java.base/java.lang.Thread.run(Thread.java:834)
The code that receives the file does not stop after reading the first file, but keeps reading until the end of the stream, writing everything that's sent to the same file.
You need to keep track of how many bytes you've already read and/or how many bytes you still have to read:
int remainingBytes = length;
while (remainingBytes > 0 && (c = dis.read(buffer, 0, Math.min(buffer.length, remainingBytes))) > 0)
{
remainingBytes -= c;
fos.write(buffer, 0, c);
// fos.flush(); this is not really necessary
}
By the way, using int for file length limits you to files of at most 2GB. If this is a problem, use long instead of int.
I am writing a file upload Java app, and my issue is that my buffered writer is writing files short of their complete file size. When I record the bytes written, new file size vs old file size - there is always a difference - my buffered reader stops short based on the buffer size.
So when my buffer is set to 1024 for example - it only writes increments of 1024, but not the remaining bytes (the last few bytes that are less than 1024 bytes). DOCX (all X Office Files) are picky about their file size and when you write them short, they get flagged in office as corrupted.
int originalSize = (int) file.length();
FileInputStream fis = null;
BufferedOutputStream bout = null;
BufferedInputStream bin = null;
FileOutputStream fout = null;
try {
fis = new FileInputStream(file);
fout = new FileOutputStream(newfile);
bout = new BufferedOutputStream(fout);
bin = new BufferedInputStream(fis);
log.info("Setting buffer to 1024");
int total = 0;
byte buf[] = new byte[1024]; // Buffer Size (works when set to 1)
while((bin.read(buf)) != -1) {
Float size = (float) newfile.length();
bout.write(buf);
total += buf.length;
log.info("LOOP: Current Size:" + total + " New File Size: " + size + " Original Size: " + originalSize);
}
int size = (int) newfile.length();
log.info("new file size bytes: " + size);
log.info("original file size bytes: " + originalSize);
log.info("File created: " + newfile.getName());
return newfile.getName();
} catch (Exception e) {
log.error("ERROR: during input output file streaming: " + e.getMessage());
} finally {
fis.close();
bout.close();
bin.close();
}
So this works when I set the Buffer Size to 1 byte because it will completely write out the file
Any suggestions how I can get a buffered writer like this (I have to buffer it / use streams because it handles massive files) to write out the exact ammount of bytes for that file, It would be much appreciated.
Thanks
The read() method returns the number of bytes read. The buffer isn't always fully filled.
You should write something like this:
int bytesRead = 0;
while((bytesRead = bin.read(buf)) != -1) {
bout.write(buf, 0, bytesRead); // Write only the bytes read
total += bytesRead;
// ...
}
Read an audio file, for example a wav file, then get its time length. Then get its bytes value from second by second, or by half a second. Like I have a 20 seconds wav and i will output its bytes[] by the time I specified. Because getting the bytes for all the length of the file takes very large of space.
This is me getting the bytes from the audio file, but i need just the bytes by its seconds. Any help?
FileInputStream s = new FileInputStream(Environment.getExternalStorageDirectory().getAbsolutePath()+"/audio_raw.wav");
BufferedInputStream b = new BufferedInputStream(s);
byte[] data = new byte[128];
while((bytes = b.read(data)) > 0)
{
for(int i = 0; i<bytes; i++)
{
unsigned = data[i] & 0xFF;
bw.write(unsigned+"+");
}
}
b.read(data);
b.close();
This is a function from a class that processes WAV files I use. You can see how it reads in the file and can extract some data about the WAV file. Perhaps it can assist you:
// read a wav file into this class
public boolean read()
{
DataInputStream inFile = null;
myData = null;
byte[] tmpLong = new byte[4];
byte[] tmpInt = new byte[2];
try
{
inFile = new DataInputStream(new FileInputStream(myPath));
//System.out.println("Reading wav file...\n"); // for debugging only
String chunkID = "" + (char) inFile.readByte() + (char) inFile.readByte() + (char) inFile.readByte() + (char) inFile.readByte();
inFile.read(tmpLong); // read the ChunkSize
myChunkSize = byteArrayToLong(tmpLong);
String format = "" + (char) inFile.readByte() + (char) inFile.readByte() + (char) inFile.readByte() + (char) inFile.readByte();
// print what we've read so far
//System.out.println("chunkID:" + chunkID + " chunk1Size:" + myChunkSize + " format:" + format); // for debugging only
String subChunk1ID = "" + (char) inFile.readByte() + (char) inFile.readByte() + (char) inFile.readByte() + (char) inFile.readByte();
inFile.read(tmpLong); // read the SubChunk1Size
mySubChunk1Size = byteArrayToLong(tmpLong);
inFile.read(tmpInt); // read the audio format. This should be 1 for PCM
myFormat = byteArrayToInt(tmpInt);
inFile.read(tmpInt); // read the # of channels (1 or 2)
myChannels = byteArrayToInt(tmpInt);
inFile.read(tmpLong); // read the samplerate
mySampleRate = byteArrayToLong(tmpLong);
inFile.read(tmpLong); // read the byterate
myByteRate = byteArrayToLong(tmpLong);
inFile.read(tmpInt); // read the blockalign
myBlockAlign = byteArrayToInt(tmpInt);
inFile.read(tmpInt); // read the bitspersample
myBitsPerSample = byteArrayToInt(tmpInt);
// print what we've read so far
//System.out.println("SubChunk1ID:" + subChunk1ID + " SubChunk1Size:" + mySubChunk1Size + " AudioFormat:" + myFormat + " Channels:" + myChannels + " SampleRate:" + mySampleRate);
// read the data chunk header - reading this IS necessary, because not all wav files will have the data chunk here - for now, we're just assuming that the data chunk is here
String dataChunkID = "" + (char) inFile.readByte() + (char) inFile.readByte() + (char) inFile.readByte() + (char) inFile.readByte();
inFile.read(tmpLong); // read the size of the data
myDataSize = byteArrayToLong(tmpLong);
// read the data chunk
myData = new byte[(int) myDataSize];
inFile.read(myData);
// close the input stream
inFile.close();
}
catch (Exception e)
{
return false;
}
return true; // this should probably be something more descriptive
}
I have to use java.nio to create a file of any desired size by populating it with data. I am reading through a document, but am confused about when I need to flip, put, or write and am getting errors. I have successfully done this program using .io but I am testing to see if .nio will make it run faster.
This is my code so far. args[0] is the size of the file you want to make and args[1] is the name of the file to be written to
public static void main(String[] args) throws IOException
{
nioOutput fp = new nioOutput();
FileOutputStream fos = new FileOutputStream(args[1]);
FileChannel fc = fos.getChannel();
long sizeOfFile = fp.getFileSize(args[1]);
long desiredSizeOfFile = Long.parseLong(args[0]) * 1073741824; //1 Gigabyte = 1073741824 bytes
int byteLength = 1024;
ByteBuffer b = ByteBuffer.allocate(byteLength);
while(sizeOfFile + byteLength < desiredSizeOfFile)
{
// b.put((byte) byteLength);
b.flip();
fc.write(b);
sizeOfFile += byteLength;
}
int diff = (int) (desiredSizeOfFile - sizeOfFile);
sizeOfFile += diff;
fc.write(b, 0, diff);
fos.close();
System.out.println("Finished at " + sizeOfFile / 1073741824 + " Gigabyte(s)");
}
long getFileSize(String fileName)
{
File file = new File(fileName);
if (!file.exists() || !file.isFile())
{
System.out.println("File does not exist");
return -1;
}
return file.length();
}
If all you want to do is pre-extend a file to a given length with nulls, you can do it in three lines and save all that I/O:
RandomAccessFile raf = new RandomAccessFile(file, "rw");
raf.setLength(desiredSizeOfFile);
raf.close();
This will operate several gazzilion times as quickly as what you are trying to do now.
sorry everyone, I figured it out.
while(sizeOfFile + byteLength < desiredSizeOfFile)
{
fc.write(b);
b.rewind();
sizeOfFile += byteLength;
}
int diff = (int) (desiredSizeOfFile - sizeOfFile);
sizeOfFile += diff;
ByteBuffer d = ByteBuffer.allocate(diff);
fc.write(d);
b.rewind();
fos.close();
System.out.println("Finished at " + sizeOfFile / 1073741824 + " Gigabyte(s)");
}
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
I would like to write the Wav file from byte array and I also want to split channels from the input wav file
The Java Sound API shows that you can record music from a TargetDataLine and as an example shows the data being written to a byte array. But writing this byte array out into its own file is fairly useless since it is not in the WAV file format and cannot be played in other applications.
How do I write sound files using the javax.sound.sampled package?
I have used this in the past for going from Wav -> byte[] and byte[] -> Wav
package GlobalUtilities;
import java.applet.Applet;
import java.applet.AudioClip;
import java.net.URISyntaxException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.io.*;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import javax.sound.sampled.*;
/**
* This class handles the reading, writing, and playing of wav files. It is
* also capable of converting the file to its raw byte [] form.
*
* based on code by Evan Merz modified by Dan Vargo
* #author dvargo
*/
public class Wav {
/*
WAV File Specification
FROM http://ccrma.stanford.edu/courses/422/projects/WaveFormat/
The canonical WAVE format starts with the RIFF header:
0 4 ChunkID Contains the letters "RIFF" in ASCII form
(0x52494646 big-endian form).
4 4 ChunkSize 36 + SubChunk2Size, or more precisely:
4 + (8 + SubChunk1Size) + (8 + SubChunk2Size)
This is the size of the rest of the chunk
following this number. This is the size of the
entire file in bytes minus 8 bytes for the
two fields not included in this count:
ChunkID and ChunkSize.
8 4 Format Contains the letters "WAVE"
(0x57415645 big-endian form).
The "WAVE" format consists of two subchunks: "fmt " and "data":
The "fmt " subchunk describes the sound data's format:
12 4 Subchunk1ID Contains the letters "fmt "
(0x666d7420 big-endian form).
16 4 Subchunk1Size 16 for PCM. This is the size of the
rest of the Subchunk which follows this number.
20 2 AudioFormat PCM = 1 (i.e. Linear quantization)
Values other than 1 indicate some
form of compression.
22 2 NumChannels Mono = 1, Stereo = 2, etc.
24 4 SampleRate 8000, 44100, etc.
28 4 ByteRate == SampleRate * NumChannels * BitsPerSample/8
32 2 BlockAlign == NumChannels * BitsPerSample/8
The number of bytes for one sample including
all channels. I wonder what happens when
this number isn't an integer?
34 2 BitsPerSample 8 bits = 8, 16 bits = 16, etc.
The "data" subchunk contains the size of the data and the actual sound:
36 4 Subchunk2ID Contains the letters "data"
(0x64617461 big-endian form).
40 4 Subchunk2Size == NumSamples * NumChannels * BitsPerSample/8
This is the number of bytes in the data.
You can also think of this as the size
of the read of the subchunk following this
number.
44 * Data The actual sound data.
The thing that makes reading wav files tricky is that java has no unsigned types. This means that the
binary data can't just be read and cast appropriately. Also, we have to use larger types
than are normally necessary.
In many languages including java, an integer is represented by 4 bytes. The issue here is
that in most languages, integers can be signed or unsigned, and in wav files the integers
are unsigned. So, to make sure that we can store the proper values, we have to use longs
to hold integers, and integers to hold shorts.
Then, we have to convert back when we want to save our wav data.
It's complicated, but ultimately, it just results in a few extra functions at the bottom of
this file. Once you understand the issue, there is no reason to pay any more attention
to it.
ALSO:
This code won't read ALL wav files. This does not use to full specification. It just uses
a trimmed down version that most wav files adhere to.
*/
ByteArrayOutputStream byteArrayOutputStream;
AudioFormat audioFormat;
TargetDataLine targetDataLine;
AudioInputStream audioInputStream;
SourceDataLine sourceDataLine;
float frequency = 8000.0F; //8000,11025,16000,22050,44100
int samplesize = 16;
private String myPath;
private long myChunkSize;
private long mySubChunk1Size;
private int myFormat;
private long myChannels;
private long mySampleRate;
private long myByteRate;
private int myBlockAlign;
private int myBitsPerSample;
private long myDataSize;
// I made this public so that you can toss whatever you want in here
// maybe a recorded buffer, maybe just whatever you want
public byte[] myData;
public Wav()
{
myPath = "";
}
// constructor takes a wav path
public Wav(String tmpPath) {
myPath = tmpPath;
}
// get/set for the Path property
public String getPath()
{
return myPath;
}
public void setPath(String newPath)
{
myPath = newPath;
}
// read a wav file into this class
public boolean read() {
DataInputStream inFile = null;
myData = null;
byte[] tmpLong = new byte[4];
byte[] tmpInt = new byte[2];
try {
inFile = new DataInputStream(new FileInputStream(myPath));
//System.out.println("Reading wav file...\n"); // for debugging only
String chunkID = "" + (char) inFile.readByte() + (char) inFile.readByte() + (char) inFile.readByte() + (char) inFile.readByte();
inFile.read(tmpLong); // read the ChunkSize
myChunkSize = byteArrayToLong(tmpLong);
String format = "" + (char) inFile.readByte() + (char) inFile.readByte() + (char) inFile.readByte() + (char) inFile.readByte();
// print what we've read so far
//System.out.println("chunkID:" + chunkID + " chunk1Size:" + myChunkSize + " format:" + format); // for debugging only
String subChunk1ID = "" + (char) inFile.readByte() + (char) inFile.readByte() + (char) inFile.readByte() + (char) inFile.readByte();
inFile.read(tmpLong); // read the SubChunk1Size
mySubChunk1Size = byteArrayToLong(tmpLong);
inFile.read(tmpInt); // read the audio format. This should be 1 for PCM
myFormat = byteArrayToInt(tmpInt);
inFile.read(tmpInt); // read the # of channels (1 or 2)
myChannels = byteArrayToInt(tmpInt);
inFile.read(tmpLong); // read the samplerate
mySampleRate = byteArrayToLong(tmpLong);
inFile.read(tmpLong); // read the byterate
myByteRate = byteArrayToLong(tmpLong);
inFile.read(tmpInt); // read the blockalign
myBlockAlign = byteArrayToInt(tmpInt);
inFile.read(tmpInt); // read the bitspersample
myBitsPerSample = byteArrayToInt(tmpInt);
// print what we've read so far
//System.out.println("SubChunk1ID:" + subChunk1ID + " SubChunk1Size:" + mySubChunk1Size + " AudioFormat:" + myFormat + " Channels:" + myChannels + " SampleRate:" + mySampleRate);
// read the data chunk header - reading this IS necessary, because not all wav files will have the data chunk here - for now, we're just assuming that the data chunk is here
String dataChunkID = "" + (char) inFile.readByte() + (char) inFile.readByte() + (char) inFile.readByte() + (char) inFile.readByte();
inFile.read(tmpLong); // read the size of the data
myDataSize = byteArrayToLong(tmpLong);
// read the data chunk
myData = new byte[(int) myDataSize];
inFile.read(myData);
// close the input stream
inFile.close();
} catch (Exception e) {
return false;
}
return true; // this should probably be something more descriptive
}
// write out the wav file
public boolean save() {
try {
DataOutputStream outFile = new DataOutputStream(new FileOutputStream(myPath + "temp"));
// write the wav file per the wav file format
outFile.writeBytes("RIFF"); // 00 - RIFF
outFile.write(intToByteArray((int) myChunkSize), 0, 4); // 04 - how big is the rest of this file?
outFile.writeBytes("WAVE"); // 08 - WAVE
outFile.writeBytes("fmt "); // 12 - fmt
outFile.write(intToByteArray((int) mySubChunk1Size), 0, 4); // 16 - size of this chunk
outFile.write(shortToByteArray((short) myFormat), 0, 2); // 20 - what is the audio format? 1 for PCM = Pulse Code Modulation
outFile.write(shortToByteArray((short) myChannels), 0, 2); // 22 - mono or stereo? 1 or 2? (or 5 or ???)
outFile.write(intToByteArray((int) mySampleRate), 0, 4); // 24 - samples per second (numbers per second)
outFile.write(intToByteArray((int) myByteRate), 0, 4); // 28 - bytes per second
outFile.write(shortToByteArray((short) myBlockAlign), 0, 2); // 32 - # of bytes in one sample, for all channels
outFile.write(shortToByteArray((short) myBitsPerSample), 0, 2); // 34 - how many bits in a sample(number)? usually 16 or 24
outFile.writeBytes("data"); // 36 - data
outFile.write(intToByteArray((int) myDataSize), 0, 4); // 40 - how big is this data chunk
outFile.write(myData); // 44 - the actual data itself - just a long string of numbers
} catch (Exception e) {
System.out.println(e.getMessage());
return false;
}
return true;
}
// return a printable summary of the wav file
public String getSummary() {
//String newline = System.getProperty("line.separator");
String newline = "";
String summary = "Format: " + myFormat + newline + "Channels: " + myChannels + newline + "SampleRate: " + mySampleRate + newline + "ByteRate: " + myByteRate + newline + "BlockAlign: " + myBlockAlign + newline + "BitsPerSample: " + myBitsPerSample + newline + "DataSize: " + myDataSize + "";
return summary;
}
public byte[] getBytes() {
read();
return myData;
}
/**
* Plays back audio stored in the byte array using an audio format given by
* freq, sample rate, ect.
* #param data The byte array to play
*/
public void playAudio(byte[] data) {
try {
byte audioData[] = data;
//Get an input stream on the byte array containing the data
InputStream byteArrayInputStream = new ByteArrayInputStream(audioData);
AudioFormat audioFormat = getAudioFormat();
audioInputStream = new AudioInputStream(byteArrayInputStream, audioFormat, audioData.length / audioFormat.getFrameSize());
DataLine.Info dataLineInfo = new DataLine.Info(SourceDataLine.class, audioFormat);
sourceDataLine = (SourceDataLine) AudioSystem.getLine(dataLineInfo);
sourceDataLine.open(audioFormat);
sourceDataLine.start();
//Create a thread to play back the data and start it running. It will run \
//until all the data has been played back.
Thread playThread = new Thread(new PlayThread());
playThread.start();
} catch (Exception e) {
System.out.println(e);
}
}
/**
* 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.
* #return
*/
private AudioFormat getAudioFormat() {
float sampleRate = frequency;
//8000,11025,16000,22050,44100
int sampleSizeInBits = samplesize;
//8,16
int channels = 1;
//1,2
boolean signed = true;
//true,false
boolean bigEndian = false;
//true,false
//return new AudioFormat( AudioFormat.Encoding.PCM_SIGNED, 8000.0f, 8, 1, 1,
//8000.0f, false );
return new AudioFormat(sampleRate, sampleSizeInBits, channels, signed, bigEndian);
}
public void playWav(String filePath) {
try {
AudioClip clip = (AudioClip) Applet.newAudioClip(new File(filePath).toURI().toURL());
clip.play();
} catch (Exception e) {
Logger.getLogger(Wav.class.getName()).log(Level.SEVERE, null, e);
}
}
// ===========================
// CONVERT BYTES TO JAVA TYPES
// ===========================
// these two routines convert a byte array to a unsigned short
public static int byteArrayToInt(byte[] b) {
int start = 0;
int low = b[start] & 0xff;
int high = b[start + 1] & 0xff;
return (int) (high > 8) & 0x000000FF);
b[2] = (byte) ((i >> 16) & 0x000000FF);
b[3] = (byte) ((i >> 24) & 0x000000FF);
return b;
}
// convert a short to a byte array
public static byte[] shortToByteArray(short data) {
return new byte[]{(byte) (data & 0xff), (byte) ((data >>> 8) & 0xff)};
}
/**
* Inner class to play back the data that was saved
*/
class PlayThread extends Thread {
byte tempBuffer[] = new byte[10000];
public void run() {
try {
int cnt;
//Keep looping until the input
// read method returns -1 for
// empty stream.
while ((cnt = audioInputStream.read(tempBuffer, 0, tempBuffer.length)) != -1) {
if (cnt > 0) {
//Write data to the internal
// buffer of the data line
// where it will be delivered
// to the speaker.
sourceDataLine.write(tempBuffer, 0, cnt);
}
}
//Block and wait for internal
// buffer of the data line to
// empty.
sourceDataLine.drain();
sourceDataLine.close();
} catch (Exception e) {
System.out.println(e);
System.exit(0);
}
}
}
}
Writing file from InputStream to OutputStream by reading bytes:
File srcFile = new File("c:/src.wav");
File dstFile = new File("c:/dst.wav");
FileInputStream in = new FileInputStream(srcFile);
FileOutputStream out = new FileOutputStream(dstFile);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
And here are some already answered questions on splitting wav channels, may be of use:
How to split a Wav file into channels in java?
wav amplitude in java (stereo or more channels)