user2335004
user2335004

Reputation: 121

Reading excel 2007 and writing file in java

I want to retrieve file from ftp server, I have also used Apache poi client.retrieveFile() method, but I'm unable to open it which is showing:

excel cannot open file check file extension and file format. check file is not corrupted

Then I used file reader and writer. Below is my code snippet.

public void testFileWriter()
    {
        try{

        FTPFile[] files = client.listFiles("/Ftp1");
        for (FTPFile file : files) {
            File serverFile = new File("D:/Pondi.xlsx");
            if(!serverFile.isFile())
            {
                serverFile.createNewFile();
            }
            BufferedWriter writer = new BufferedWriter(new FileWriter(serverFile));
            client.enterLocalPassiveMode();
            InputStream inputStream = client.retrieveFileStream("/Ftp1/"+ file.getName());
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            System.out.println("Created Reader");
            while(reader.read()!=-1)
            {
                String temp = reader.readLine();
                System.out.println(temp);


                writer.write(temp);
            }
            writer.flush();
            writer.close();
            reader.close();
        }

        }
        catch(IOException ioe){
            ioe.printStackTrace();
        }
    }

Please help me to resolve this crucial issue.

Upvotes: 0

Views: 1289

Answers (2)

Maximin
Maximin

Reputation: 1685

You have to use an API for working with it. You can't read these files like reading normal text files.

JExcel will be good for your need.

Examples are be available here

For copying files make use of this. Reading the file for copying by the method that you used won't work properly.

Hope will be helpful for you.

Upvotes: 2

Uooo
Uooo

Reputation: 6354

If you want to read and copy binary data, you must not use reader.readLine(), because there are no lines in a binary file. Therefore, this attempt will most likely fail.

Copy it like this instead:

int fileNo = 0;
for (FTPFile file : files) {
    File serverFile = new File("D:/Pondi_" + fileNo + ".xlsx");
    ...
    InputStream in = client.retrieveFileStream("/Ftp1/"+ file.getName());
    OutputStream out = new FileOutputStream(serverFile);

    // read and copy binary data
    byte[] buf = new byte[1024];
    int len;
    while ((len = in.read(buf)) > 0){
        out.write(buf, 0, len);
    }

    in.close();
    out.close();
    fileNo++;
}

Beside that, consider giving your files a different name that D:/Pondi.xlsx, because otherwise the file gets overridden again and again in the loop. I did this with fileNo.

Upvotes: 1

Related Questions