It is necessary to read data from two streams and write to one.

FileOutputStream file1 = new FileOutputStream("D:\\file1.txt"); SequenceInputStream sequance = new SequenceInputStream(new FileInputStream("D:\\file3.txt"), new FileInputStream("D:\\file2.txt")); int size = sequance.available(); int reading = 0; byte[] buffer = new byte[size]; if(sequance.available() > 0) { reading = sequance.read(buffer, 0, size); file1.write(buffer, 0, reading); } sequance.close(); file1.close(); } catch (IOException ex){ex.printStackTrace();} 

Reads only from the first stream, if the threads in the constructor are reversed, then again reads only from the first stream (in the resulting file, the data only from the first stream made debug, the size variable is equal to the number of characters in the first stream). Where is the mistake?

    2 answers 2

    Your stumbling block is the string int size = sequance.available(); And to be more precise, the .available() method itself, as far as I remember, it returns the number of available bits in one / current stream, but what happens next should be clear. The buffer is small for data from two files

    UPD:

    It can be read that it can be read. The next invocation might be the same thread or another thread. It can be a bit more than one.

    example of your code (working) without streams and buffers

     FileOutputStream file1 = new FileOutputStream("/home/peter/git/1.txt", true); @SuppressWarnings("resource") SequenceInputStream sequance = new SequenceInputStream( new FileInputStream(new File("/home/peter/git/3.txt")), new FileInputStream("/home/peter/git/2.txt")); int reading = 0; while ((reading = sequance.read()) != -1) { System.out.println(reading); file1.write(reading); } sequance.close(); file1.close(); 
       sequance.read(buffer, 0, size); 

      reads only a portion of the data, with a length of at least 1 and no more than the size of the buffer. How much is specifically at the discretion of implementation. To read everything, a cycle is always necessary.

      By the way, available () gives only an estimate, not the exact size of the data available. And you do not need this assessment at all.

      • With a cycle too tried, instead of if, the same situation. The error appears already on the line of calculation of the variable size. - diana.oryol