2

Please have a look at the following code

    import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class FileCopy2
{    public static void main(String[]args) 
    {        
        try
        {

              //First in here, we are trying to get the bytes from the file


        File file = new File("D:/burn/preview.mp3"); //The File you need to get

        byte bufferFile[] = new byte[(int)file.length()]; //Creating a byte array, which has the exact size of the file

        BufferedInputStream bi = new BufferedInputStream(new FileInputStream(file));// Creating Buffers for IO

        bi.read(bufferFile, 0, bufferFile.length);//Reading the file

        bi.close();//Closing Buffer




        //Then in here, we are writing those bytes to a text file

        BufferedOutputStream bu = new BufferedOutputStream(new FileOutputStream("C:/Users/Yohan/Desktop/test.txt")); //The output Location
        bu.write(bufferFile, 0, bufferFile.length);//Writing the file
        bu.flush();//Flushing the buffer
        bu.close();//Closing the Buffer

        System.out.println("Done Copieng");



        //Here we are trying to WRITE number of .txt files containing the byte details..In other words, I am breaking the file into peaces

        BufferedReader br = new BufferedReader(new FileReader("C:/Users/Yohan/Desktop/test.txt"));
        BufferedWriter bw = null;

        String content = "";
        int count = 1;
        while((content = br.readLine())!=null)
        {

            bw = new BufferedWriter(new FileWriter("C:/Users/Yohan/Desktop/output4/file"+count+".txt"));
            bw.write(content);
            bw.flush();
            bw.close();


            count++;
            System.out.println("Running");

        }
        System.out.println("-----------------------Done-----------------------------");



            //NOW I NEED TO read all the generated .txt file and create the original file back. How to do it? //
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }
}

In there, first I get the bytes of a file, and write them to a text file. Then I read that text file, read line by line, and generate a separate .txt file for each line. Now the original program is split into thousands of files. Now I need to read all the .txt files and re generate the .txt file. I don't know how to do the last thing. How can I do that? Please help!

6
  • 5
    This program doesn't make sense. An mp3 file contains binary data, not textual data. It makes no sense to write and read it as text. Moreover, you have absolutely no guarantee that you read all the file, since you ignore the result of the read() call, and don't loop until you've read everything. And finally, you don't close your streams in finally blocks. Google for "Java IO tutorial". Commented Jun 2, 2012 at 15:27
  • @Polygnome: Whats your answers? Commented Jun 2, 2012 at 15:45
  • 1
    @JBNizet: I know it contains binary data and thats why I got the bytes. If you change the file parameters (which means give ""C:/Users/Yohan/Desktop/test.txt" to the first block and "D:/burn/preview.mp3" to the second block), after running this code first. It will regenerate the original file, I have tested it and it worked all the time. Please be kind enough to provide an answer if you know Commented Jun 2, 2012 at 15:51
  • 2
    Just because you can transform any encoded character sequence into a sequence of bytes doesn't mean you can transform any sequence of byte into a valid encoded character sequence. Your program makes no sense, and there is no valid answer to your question. Suppose your encoding is ASCII, which considers all bytes from 128 to 255 as invalid characters. You're trying to transform an mp3 file which contains such bytes into ASCII, and you will thus lose half of the bytes of your mp3 file. Commented Jun 2, 2012 at 16:01
  • If you changed the specification to text file only, for both input & output, people could provide answers. Even given that, what you would be doing makes little sense. Why disassemble a file into each line, only to reassemble it? What program feature are you trying to offer through all this effort? Commented Jun 2, 2012 at 16:06

1 Answer 1

10

If you want to manipulate any kind of file, never consider they contain textual data, and consider them as binary files, containing bytes. Binary files are read and written using input and output streams.

Here's an example of a method that reads a file and splits it into pieces of 1024 bytes written to N output files :

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileSplit {
    public static void main(String[] args) throws IOException {
        new FileSplit().splitFile(new File(args[0]));
    }

    private void splitFile(File file) throws IOException {
        FileInputStream fis = new FileInputStream(file);
        try {
            byte[] buffer = new byte[1024];
            // remaining is the number of bytes to read to fill the buffer
            int remaining = buffer.length; 
            // block number is incremented each time a block of 1024 bytes is read 
            //and written
            int blockNumber = 1;
            while (true) {
                int read = fis.read(buffer, buffer.length - remaining, remaining);
                if (read >= 0) { // some bytes were read
                    remaining -= read;
                    if (remaining == 0) { // the buffer is full
                        writeBlock(blockNumber, buffer, buffer.length - remaining);
                        blockNumber++;
                        remaining = buffer.length;
                    }
                }
                else { 
                    // the end of the file was reached. If some bytes are in the buffer
                    // they are written to the last output file
                    if (remaining < buffer.length) {
                        writeBlock(blockNumber, buffer, buffer.length - remaining);
                    }
                    break;
                }
            }
        }
        finally {
            fis.close();
        }
    }

    private void writeBlock(int blockNumber, byte[] buffer, int length) throws IOException {
        FileOutputStream fos = new FileOutputStream("output_" + blockNumber + ".dat");
        try {
            fos.write(buffer, 0, length);
        }
        finally {
            fos.close();
        }
    }
}
Sign up to request clarification or add additional context in comments.

5 Comments

First, I beg your apologies for the delay. I am glad to see a code example! Please give me a day to check out whether this is the one I am seeking for. I am unable to do it now because it is 1 AM :)
wow..OK..This is the answer. Thanks a lot. I really appreciate it :)
In this program if the file has only 1000 bytes, during first iteration it will read 1000 bytes, whereas remaining is 1024. So remaining-=read will make remaining as 24. So the condition if(remaining == 0) will be false, It will goto next iteration without writing. Next iteration read will be -1, so the loop breaks. So it will close the input stream without writing what it has read.It is my doubt, please correct me if I am wrong (In a soft tone plss)
No. The second iteration will read -1, so the else block will be executed, and the else block will write what has been read, and then only the loop will end. Test it.
Great! this is a good answer the code shows everything the question needs, i was also searching for something like this, got it now..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.