簡體   English   中英

使用 jar 文件在臨時文件夾中創建 excel 文件時,Excel 文件損壞

[英]Excel File is getting corrupted when Creating a excel file in temp folder using jar file

我已經創建了一個 jar 文件,該文件將使用 Z2DAC15048 文件中存在的 excel 文件的 inputStream 在臨時文件夾中創建一個 excel 文件。 我有 2 個 excel 文件。 一個 excel 文件大小為 35kb,2 張,另一個 excel 文件大小為 53kb,3 張。 當我使用 Eclipse 運行時,文件正在臨時文件夾中創建而沒有任何問題,但是當我使用 jar 文件執行相同操作時。 53Kb 大小的文件已損壞。 有人對此有任何想法嗎,

代碼片段

InputStream is=Test.class.getClassLoader().getResourceAsStream("New_User_Datasheet.xls");

文件創建片段

public File createFile(InputStream inStream, String fileName, String fileExtn) throws IOException {
        byte[] buffer = new byte[inStream.available()];
         inStream.read(buffer);
        if (!(new File(String.valueOf(System.getProperty("java.io.tmpdir")) + "\\Resources")).exists()) {
             File tempFile = new File(
                    String.valueOf(System.getProperty("java.io.tmpdir")) + "\\Resources");
                tempFile.mkdir();
                try {
                 Thread.sleep(1000L);
                 } catch (InterruptedException e) {
                     e.printStackTrace();
                 }
         }
         String file = "";
            try {
                File Parent = new File(
                    String.valueOf(System.getProperty("java.io.tmpdir")) + "\\Resources");
                File temp = new File(Parent, String.valueOf(fileName) + fileExtn);
                if (temp.exists())
                    temp.delete();
                temp.createNewFile();
             Thread.sleep(1000L);
             file = temp.getAbsolutePath();
             Files.write(buffer, temp);
             } catch (Exception e) 
            {
                 e.printStackTrace();
             }
            return new File(file);
         }

我在 Google 中找到了解決方案,我將 InputStream 寫為 OutputStream 而不是 BufferReader。

代碼片段

 OutputStream os = new FileOutputStream("/Users/pankaj/new_source.txt");
            
            byte[] buffer = new byte[1024];
            int bytesRead;
            //read from is to buffer
            while((bytesRead = is.read(buffer)) !=-1){
                os.write(buffer, 0, bytesRead);
            }
            is.close();
            //flush OutputStream to write any buffered data to file
            os.flush();
            os.close();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM