Example usage for org.apache.poi.poifs.filesystem POIFSFileSystem close

List of usage examples for org.apache.poi.poifs.filesystem POIFSFileSystem close

Introduction

In this page you can find the example usage for org.apache.poi.poifs.filesystem POIFSFileSystem close.

Prototype

@Override
public void close() throws IOException 

Source Link

Document

Closes the FileSystem, freeing any underlying files, streams and buffers.

Usage

From source file:com.vodafone.poms.ii.helpers.ExportManager.java

private static String addFile(XSSFSheet sh, String filePath, double oleId)
        throws IOException, InvalidFormatException {
    File file = new File(filePath);
    FileInputStream fin = new FileInputStream(file);
    byte[] data;/*from   w ww . j  av  a2 s .  c  om*/
    data = new byte[fin.available()];
    fin.read(data);
    Ole10Native ole10 = new Ole10Native(file.getAbsolutePath(), file.getAbsolutePath(), file.getAbsolutePath(),
            data);

    ByteArrayOutputStream bos = new ByteArrayOutputStream(500);
    ole10.writeOut(bos);

    POIFSFileSystem poifs = new POIFSFileSystem();
    poifs.getRoot().createDocument(Ole10Native.OLE10_NATIVE, new ByteArrayInputStream(bos.toByteArray()));

    poifs.getRoot().setStorageClsid(ClassID.OLE10_PACKAGE);

    final PackagePartName pnOLE = PackagingURIHelper
            .createPartName("/xl/embeddings/oleObject" + oleId + Math.random() + ".bin");
    final PackagePart partOLE = sh.getWorkbook().getPackage().createPart(pnOLE,
            "application/vnd.openxmlformats-officedocument.oleObject");
    PackageRelationship prOLE = sh.getPackagePart().addRelationship(pnOLE, TargetMode.INTERNAL,
            POIXMLDocument.OLE_OBJECT_REL_TYPE);
    OutputStream os = partOLE.getOutputStream();
    poifs.writeFilesystem(os);
    os.close();
    poifs.close();

    return prOLE.getId();

}

From source file:Creator.TaskManagerPanel.java

/**
 * Reads a file and returns a list of strings which contain all the variable
 * names/*from  w  w w.j a  va 2s .c  om*/
 *
 * @param filename
 */
public void readXFile(String filename) {

    try {

        POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(filename));
        HSSFWorkbook wb = new HSSFWorkbook(fs);
        HSSFSheet sheet = wb.getSheetAt(0);
        HSSFRow row;
        HSSFCell cell;

        int rows; // No of rows
        rows = sheet.getPhysicalNumberOfRows();

        int cols = 0; // No of columns
        int tmp = 0;

        int idCol = -1, idName = -1;
        // This trick ensures that we get the data properly even if it doesn't start from first few rows
        for (int i = 0; i < 1; i++) {
            row = sheet.getRow(i);
            if (row != null) {
                tmp = sheet.getRow(i).getPhysicalNumberOfCells();
                if (tmp > cols) {
                    cols = tmp;
                }
            }

            if (!sheet.getRow(i).getCell(0).toString().equals("io_id")) {
                for (int c = 1; c < cols; c++) {
                    if (sheet.getRow(i).getCell(c).equals("io_id")) {
                        idCol = c;
                        break;
                    }
                }
            } else {
                idCol = 0;
            }

            if (!sheet.getRow(i).getCell(1).toString().equals("io_name")) {
                for (int c = 0; c < cols; c++) {
                    if (sheet.getRow(i).getCell(c).equals("io_name")) {
                        idName = c;
                        break;
                    }
                }
            } else {
                idName = 1;
            }

            if (!sheet.getRow(i).getCell(2).toString().equals("io_station_id")) {
                for (int c = 0; c < cols; c++) {
                    if (sheet.getRow(i).getCell(c).equals("io_station_id")) {
                        stationID = (int) sheet.getRow(1).getCell(c).getNumericCellValue();
                        break;
                    }
                }
            } else {
                stationID = (int) sheet.getRow(1).getCell(2).getNumericCellValue();
            }

        }

        if (idName == -1 || idCol == -1) {
            System.out.println("Could not locate io_name or io_id in excel header");
            return;
        }
        if (stationID == -1) {
            System.out.println("Couldnt locate station id");
            return;
        }

        importedIOVariables = new TreeMap<>();
        int io_id;
        String io_name;

        for (int r = 1; r < rows; r++) {
            row = sheet.getRow(r);
            if (row != null) {

                cell = row.getCell(idCol);
                if (cell != null) {
                    io_id = (int) cell.getNumericCellValue();

                    cell = row.getCell(idName);
                    if (cell != null) {
                        io_name = cell.toString().replace("\"", "");
                        // Read both name and id
                        importedIOVariables.put(io_name, io_id);
                    }
                }

            }
        }
        fs.close();
        mf.loadImportedIos(importedIOVariables, 2, stationID);
    } catch (Exception e) {
        System.out.println("Error reading excel file " + e.getMessage());
    }
}

From source file:Creator.WidgetPanel.java

/**
 * Reads a file and returns a list of strings which contain all the variable
 * names//from w  w w .  ja v a  2  s  .c om
 *
 * @param filename
 */
public void readXFile(String filename) {

    try {

        POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(filename));
        HSSFWorkbook wb = new HSSFWorkbook(fs);
        HSSFSheet sheet = wb.getSheetAt(0);
        HSSFRow row;
        HSSFCell cell;

        int rows; // No of rows
        rows = sheet.getPhysicalNumberOfRows();

        int cols = 0; // No of columns
        int tmp = 0;

        int idCol = -1, idName = -1;
        // This trick ensures that we get the data properly even if it doesn't start from first few rows
        for (int i = 0; i < 1; i++) {
            row = sheet.getRow(i);
            if (row != null) {
                tmp = sheet.getRow(i).getPhysicalNumberOfCells();
                if (tmp > cols) {
                    cols = tmp;
                }
            }

            if (!sheet.getRow(i).getCell(0).toString().equals("io_id")) {
                for (int c = 1; c < cols; c++) {
                    if (sheet.getRow(i).getCell(c).equals("io_id")) {
                        idCol = c;
                        break;
                    }
                }
            } else {
                idCol = 0;
            }
            if (!sheet.getRow(i).getCell(1).toString().equals("io_name")) {
                for (int c = 1; c < cols; c++) {
                    if (sheet.getRow(i).getCell(c).equals("io_name")) {
                        idName = c;
                        break;
                    }
                }
            } else {
                idName = 1;
            }

            if (!sheet.getRow(i).getCell(2).toString().equals("io_station_id")) {
                for (int c = 0; c < cols; c++) {
                    if (sheet.getRow(i).getCell(c).equals("io_station_id")) {
                        stationID = (int) sheet.getRow(1).getCell(c).getNumericCellValue();
                        break;
                    }
                }
            } else {
                stationID = (int) sheet.getRow(1).getCell(2).getNumericCellValue();
            }

        }

        if (idName == -1 || idCol == -1) {
            System.out.println("Could not locate io_name or io_id in excel header");
            return;
        }
        if (stationID == -1) {
            System.out.println("Couldnt locate station id");
            return;
        }

        importedIOVariables = new TreeMap<>();
        int io_id;
        String io_name;

        for (int r = 1; r < rows; r++) {
            row = sheet.getRow(r);
            if (row != null) {

                cell = row.getCell(idCol);
                if (cell != null) {
                    io_id = (int) cell.getNumericCellValue();

                    cell = row.getCell(idName);
                    if (cell != null) {
                        io_name = cell.toString().replace("\"", "");
                        // Read both name and id
                        importedIOVariables.put(io_name, io_id);
                    }
                }

            }
        }

        fs.close();

        mf.loadImportedIos(importedIOVariables, 1, stationID);

    } catch (Exception e) {
        System.out.println("Error reading excel file " + e.getMessage());
    }

}

From source file:org.knime.ext.textprocessing.nodes.source.parser.word.WordDocumentParser.java

License:Open Source License

private Document parseInternal(final InputStream is) throws Exception {
    m_currentDoc = new DocumentBuilder(m_tokenizerName);
    m_currentDoc.setDocumentFile(new File(m_docPath));
    m_currentDoc.setDocumentType(m_type);
    m_currentDoc.addDocumentCategory(m_category);
    m_currentDoc.addDocumentSource(m_source);

    POIFSFileSystem poifs = null;
    HWPFDocument hdoc = null;/*  ww  w.  j  ava  2  s.c om*/
    XWPFDocument hdoc2 = null;
    WordExtractor extractor = null;

    try {
        // doc files
        if (m_docPath.endsWith(".doc")) {
            // copy content of input stream into byte array since content have to be red twice unfortunately.
            final ByteArrayOutputStream baos = new ByteArrayOutputStream();
            final byte[] buf = new byte[1024];
            int i = 0;
            while ((i = is.read(buf)) >= 0) {
                baos.write(buf, 0, i);
            }
            final byte[] content = baos.toByteArray();

            // open stream with copied content to read text
            InputStream copiedInput = new ByteArrayInputStream(content);
            hdoc = new HWPFDocument(copiedInput);
            extractor = new WordExtractor(hdoc);
            for (String p : extractor.getParagraphText()) {
                p = p.trim();
                if (!onlyWhitepscaes(p)) {
                    m_currentDoc.addParagraph(p);
                }
            }

            // open stream again with copied content to read meta info
            copiedInput = new ByteArrayInputStream(content);
            poifs = new POIFSFileSystem(copiedInput);
            final DirectoryEntry dir = poifs.getRoot();
            final DocumentEntry siEntry = (DocumentEntry) dir.getEntry(SummaryInformation.DEFAULT_STREAM_NAME);
            final PropertySet ps = new PropertySet(new DocumentInputStream(siEntry));

            final SummaryInformation si = new SummaryInformation(ps);

            setAuthor(si.getAuthor());
            setPublicationDate(si.getCreateDateTime());

            // docx files
        } else if (m_docPath.endsWith(".docx") || m_docPath.endsWith(".docm")) {
            hdoc2 = new XWPFDocument(is);
            final List<XWPFParagraph> paragraphs = hdoc2.getParagraphs();
            for (final XWPFParagraph paragraph : paragraphs) {
                final String text = paragraph.getText();
                if (!onlyWhitepscaes(text)) {
                    m_currentDoc.addParagraph(text);
                }
            }

            setAuthor(hdoc2.getProperties().getCoreProperties().getCreator());
            setPublicationDate(hdoc2.getProperties().getCoreProperties().getCreated());
        }

        m_currentDoc.createNewSection(SectionAnnotation.CHAPTER);

        // find title
        String title = null;

        if (m_filenameAsTitle) {
            title = m_docPath.trim();
        } else {
            final List<Section> sections = m_currentDoc.getSections();
            if (sections.size() > 0) {
                try {
                    title = sections.get(0).getParagraphs().get(0).getSentences().get(0).getText().trim();
                } catch (IndexOutOfBoundsException e) {
                    LOGGER.debug("Parsed word document " + m_docPath + " is empty.");
                    title = "";
                }
            }
        }
        if (!checkTitle(title)) {
            title = m_docPath.toString();
        }
        m_currentDoc.addTitle(title);

        return m_currentDoc.createDocument();
    } finally {
        is.close();
        if (poifs != null) {
            poifs.close();
        }
        if (hdoc != null) {
            hdoc.close();
        }
        if (hdoc2 != null) {
            hdoc2.close();
        }
        if (extractor != null) {
            extractor.close();
        }
    }
}

From source file:projet_muticriteres.Fenetre.java

private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed

    final JFileChooser fc = new JFileChooser(new File("."));
    FileNameExtensionFilter filtre = new FileNameExtensionFilter("Fichier Excel", "xlsx", "xls");
    fc.setFileFilter(filtre);//w  ww.  ja va 2  s . c  o m
    File fichier;
    if (fc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
        fichier = fc.getSelectedFile();

        try {

            POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(fichier.getCanonicalPath()));

            HSSFWorkbook wb = new HSSFWorkbook(fs);
            HSSFSheet sheet = wb.getSheetAt(0);
            HSSFRow row = null;
            HSSFCell cell = null;
            double totalLigne = 0.0;
            double totalGeneral = 0.0;
            int numLigne = 1;
            int ligne = 0;
            int colonne = 0;
            int k;
            row = sheet.getRow(0);
            while (sheet.getRow(ligne) != null) {
                row = sheet.getRow(ligne);
                colonne = 0;
                k = 0;
                if (ligne == 0) {
                    colonne = 1;
                    while (row.getCell(colonne) != null) {
                        cell = row.getCell(colonne);
                        tabCriteres.add(cell.getStringCellValue());
                        colonne++;

                    }

                } else {
                    while (row.getCell(colonne) != null) {
                        cell = row.getCell(colonne);
                        if (colonne == 0) {
                            action = new Action(cell.getStringCellValue(), tabCriteres.size());
                        } else {
                            action.ajouterNote((int) cell.getNumericCellValue(), colonne - 1);
                        }
                        colonne++;
                    }
                    tabActions.add(action);
                }
                ligne++;
            }

            fs.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        /*for (int i=0; i<tabCriteres.size(); i++){
          System.out.println("critere "+i+" : "+tabCriteres.get(i));
        }
        for (int i=0; i<tabActions.size(); i++){
          System.out.println("action "+i+" : "+tabActions.get(i).getNom());
          for (int j=0; j<tabCriteres.size();j++){
              System.out.println("note"+j+":"+tabActions.get(i).getNote(j));
          }
                  
                
        }*/

        titreColonne = new String[tabCriteres.size() + 1];
        donnees = new Object[tabActions.size()][tabCriteres.size() + 1];
        titreColonne[0] = "";
        for (int i = 0; i < tabCriteres.size(); i++) {
            titreColonne[i + 1] = tabCriteres.get(i);
        }
        for (int i = 0; i < tabActions.size(); i++) {
            donnees[i][0] = tabActions.get(i).getNom();
        }
        for (int j = 0; j < tabActions.size(); j++) {
            for (int k = 1; k < tabCriteres.size() + 1; k++) {
                donnees[j][k] = tabActions.get(j).getNote(k - 1);
            }
        }
        model = new DefaultTableModel(donnees, titreColonne);
        jTable1.setModel(model);
        // this.getContentPane().add(new JScrollPane(tab));
        //this.add(tab);
        //jPanel2.add(label10);

        //jButton6.setLabel("buton");
        //jPanel2.add(jButton6);

        jTable1.setVisible(true);

        //jPanel2.repaint();

        for (int i = 0; i < tabCriteres.size() + 1; i++) {
            System.out.println("critere " + i + " : " + titreColonne[i]);
        }
        for (int i = 0; i < tabActions.size(); i++) {
            System.out.println("action " + i + " : " + donnees[i][0]);
            for (int j = 1; j < tabCriteres.size() + 1; j++) {
                System.out.println("note" + j + ":" + donnees[i][j]);
            }

        }

    }

}