List of usage examples for java.io FileNotFoundException getMessage
public String getMessage()
From source file:net.vexelon.myglob.utils.Utils.java
/** * Write input stream data to PRIVATE internal storage file. * @param context// w w w . ja v a2 s. co m * @param source * @param internalStorageName * @throws IOException */ public static void writeToInternalStorage(Context context, InputStream source, String internalStorageName) throws IOException { FileOutputStream fos = null; try { fos = context.openFileOutput(internalStorageName, Context.MODE_PRIVATE); BufferedOutputStream bos = new BufferedOutputStream(fos); BufferedInputStream bis = new BufferedInputStream(source); byte[] buffer = new byte[4096]; int read = -1; while ((read = bis.read(buffer)) != -1) { bos.write(buffer, 0, read); } bos.flush(); bos.close(); } catch (FileNotFoundException e) { throw new IOException(e.getMessage()); } finally { try { if (fos != null) fos.close(); } catch (IOException e) { } try { if (source != null) source.close(); } catch (IOException e) { } } }
From source file:com.aurel.track.exchange.docx.exporter.DocxTemplateBL.java
/** * Download the template file// www. j ava2 s. co m * @param iconBytes * @param request * @param response * @param fileName * @param inline */ public static void download(String fileName, HttpServletRequest request, HttpServletResponse response, boolean inline) { String dir = ""; File file = null; if (fileName.endsWith(".docx")) { dir = getWordTemplatesDir(); file = new File(dir + File.separator + fileName); DownloadUtil.prepareResponse(request, response, fileName, "application/vnd.openxmlformats-officedocument.wordprocessingml.document", Long.toString(file.length()), inline); } if (fileName.endsWith(".tlx") || fileName.endsWith(".zip")) { dir = getLatexTemplatesDir(); DownloadUtil.prepareResponse(request, response, fileName, "application/zip"); file = new File(dir + File.separator + fileName); } InputStream inputStream = null; OutputStream outputStream = null; try { // retrieve the file data inputStream = new FileInputStream(file); outputStream = response.getOutputStream(); byte[] buffer = new byte[BUFFER_SIZE]; int bytesRead = 0; while ((bytesRead = inputStream.read(buffer, 0, BUFFER_SIZE)) != -1) { outputStream.write(buffer, 0, bytesRead); } } catch (FileNotFoundException fnfe) { LOGGER.error("FileNotFoundException thrown " + fnfe.getMessage()); if (LOGGER.isDebugEnabled()) { LOGGER.error(ExceptionUtils.getStackTrace(fnfe)); } return; } catch (Exception ioe) { LOGGER.error("Creating the input stream failed with " + ioe.getMessage(), ioe); LOGGER.debug(ExceptionUtils.getStackTrace(ioe)); return; } finally { // flush and close the streams if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { } } if (outputStream != null) { try { outputStream.flush(); outputStream.close(); } catch (IOException e) { } } } }
From source file:co.cask.cdap.gateway.util.Util.java
/** * Read the contents of a binary file into a byte array. * * @param filename The name of the file/*from ww w. j a v a 2s.c o m*/ * @return the content of the file if successful, otherwise null */ public static byte[] readBinaryFile(String filename) { File file = new File(filename); if (!file.isFile()) { System.err.println("'" + filename + "' is not a regular file."); return null; } int bytesToRead = (int) file.length(); byte[] bytes = new byte[bytesToRead]; int offset = 0; try { FileInputStream input = new FileInputStream(filename); while (bytesToRead > 0) { int bytesRead = input.read(bytes, offset, bytesToRead); bytesToRead -= bytesRead; offset += bytesRead; } input.close(); return bytes; } catch (FileNotFoundException e) { LOG.error("File '" + filename + "' cannot be opened: " + e.getMessage()); } catch (IOException e) { LOG.error("Error reading from file '" + filename + "': " + e.getMessage()); } return bytes; }
From source file:com.cws.esolutions.security.listeners.SecurityServiceInitializer.java
/** * Initializes the security service in a standalone mode - used for applications outside of a container or when * run as a standalone jar.//from w w w . java2 s.c o m * * @param configFile - The security configuration file to utilize * @param logConfig - The logging configuration file to utilize * @param startConnections - Configure, load and start repository connections * @throws SecurityServiceException @{link com.cws.esolutions.security.exception.SecurityServiceException} * if an exception occurs during initialization */ public static void initializeService(final String configFile, final String logConfig, final boolean startConnections) throws SecurityServiceException { URL xmlURL = null; JAXBContext context = null; Unmarshaller marshaller = null; SecurityConfigurationData configData = null; final ClassLoader classLoader = SecurityServiceInitializer.class.getClassLoader(); final String serviceConfig = (StringUtils.isBlank(configFile)) ? System.getProperty("configFileFile") : configFile; final String loggingConfig = (StringUtils.isBlank(logConfig)) ? System.getProperty("secLogConfig") : logConfig; try { try { DOMConfigurator.configure(Loader.getResource(loggingConfig)); } catch (NullPointerException npx) { try { DOMConfigurator.configure(FileUtils.getFile(loggingConfig).toURI().toURL()); } catch (NullPointerException npx1) { System.err.println("Unable to load logging configuration. No logging enabled!"); System.err.println(""); npx1.printStackTrace(); } } xmlURL = classLoader.getResource(serviceConfig); if (xmlURL == null) { // try loading from the filesystem xmlURL = FileUtils.getFile(serviceConfig).toURI().toURL(); } context = JAXBContext.newInstance(SecurityConfigurationData.class); marshaller = context.createUnmarshaller(); configData = (SecurityConfigurationData) marshaller.unmarshal(xmlURL); SecurityServiceInitializer.svcBean.setConfigData(configData); if (startConnections) { DAOInitializer.configureAndCreateAuthConnection( new FileInputStream(FileUtils.getFile(configData.getSecurityConfig().getAuthConfig())), false, SecurityServiceInitializer.svcBean); Map<String, DataSource> dsMap = SecurityServiceInitializer.svcBean.getDataSources(); if (DEBUG) { DEBUGGER.debug("dsMap: {}", dsMap); } if (configData.getResourceConfig() != null) { if (dsMap == null) { dsMap = new HashMap<String, DataSource>(); } for (DataSourceManager mgr : configData.getResourceConfig().getDsManager()) { if (!(dsMap.containsKey(mgr.getDsName()))) { StringBuilder sBuilder = new StringBuilder() .append("connectTimeout=" + mgr.getConnectTimeout() + ";") .append("socketTimeout=" + mgr.getConnectTimeout() + ";") .append("autoReconnect=" + mgr.getAutoReconnect() + ";") .append("zeroDateTimeBehavior=convertToNull"); if (DEBUG) { DEBUGGER.debug("StringBuilder: {}", sBuilder); } BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName(mgr.getDriver()); dataSource.setUrl(mgr.getDataSource()); dataSource.setUsername(mgr.getDsUser()); dataSource.setConnectionProperties(sBuilder.toString()); dataSource.setPassword(PasswordUtils.decryptText(mgr.getDsPass(), mgr.getDsSalt(), configData.getSecurityConfig().getSecretAlgorithm(), configData.getSecurityConfig().getIterations(), configData.getSecurityConfig().getKeyBits(), configData.getSecurityConfig().getEncryptionAlgorithm(), configData.getSecurityConfig().getEncryptionInstance(), configData.getSystemConfig().getEncoding())); if (DEBUG) { DEBUGGER.debug("BasicDataSource: {}", dataSource); } dsMap.put(mgr.getDsName(), dataSource); } } if (DEBUG) { DEBUGGER.debug("dsMap: {}", dsMap); } SecurityServiceInitializer.svcBean.setDataSources(dsMap); } } } catch (JAXBException jx) { jx.printStackTrace(); throw new SecurityServiceException(jx.getMessage(), jx); } catch (FileNotFoundException fnfx) { fnfx.printStackTrace(); throw new SecurityServiceException(fnfx.getMessage(), fnfx); } catch (MalformedURLException mux) { mux.printStackTrace(); throw new SecurityServiceException(mux.getMessage(), mux); } catch (SecurityException sx) { sx.printStackTrace(); throw new SecurityServiceException(sx.getMessage(), sx); } }
From source file:com.webpagebytes.cms.utility.CmsConfigurationFactory.java
public static CmsConfiguration getConfiguration() { if (configuration == null) { InputStream is = null;//from w w w .j a va 2 s . c o m synchronized (lock) { try { try { is = new FileInputStream(configPath); } catch (FileNotFoundException e) { is = CmsConfigurationFactory.class.getClassLoader().getResourceAsStream(configPath); } XMLConfigReader reader = new XMLConfigReader(); configuration = reader.readConfiguration(is); } catch (Exception e) { log.log(Level.SEVERE, e.getMessage(), e); return null; } finally { IOUtils.closeQuietly(is); } } } return configuration; }
From source file:de.alpharogroup.file.read.ReadFileUtils.java
/** * The Method readHeadLine() opens the File and reads the first line from the file. * * @param inputFile//from w ww .j av a 2 s . c o m * The Path to the File and name from the file from where we read. * @return The first line from the file. */ public static String readHeadLine(final String inputFile) { BufferedReader reader = null; String headLine = null; try { reader = new BufferedReader(new FileReader(inputFile)); headLine = reader.readLine(); reader.close(); } catch (final FileNotFoundException e) { LOGGER.log(Level.SEVERE, "readHeadLine failed...\n" + e.getMessage(), e); } catch (final IOException e) { LOGGER.log(Level.SEVERE, "readHeadLine failed...\n" + e.getMessage(), e); } finally { StreamUtils.closeReader(reader); } return headLine; }
From source file:de.alpharogroup.file.read.ReadFileExtensions.java
/** * The Method readHeadLine() opens the File and reads the first line from the file. * * @param inputFile// w w w . j av a2s .co m * The Path to the File and name from the file from where we read. * @return The first line from the file. */ public static String readHeadLine(final String inputFile) { BufferedReader reader = null; String headLine = null; try { reader = new BufferedReader(new FileReader(inputFile)); headLine = reader.readLine(); reader.close(); } catch (final FileNotFoundException e) { LOGGER.log(Level.SEVERE, "readHeadLine failed...\n" + e.getMessage(), e); } catch (final IOException e) { LOGGER.log(Level.SEVERE, "readHeadLine failed...\n" + e.getMessage(), e); } finally { StreamExtensions.closeReader(reader); } return headLine; }
From source file:com.stgmastek.core.logic.ExecutionOrder.java
/** * Reads the saved state of the batch for revision runs * If the current batch number it 1000 and revision is 5, * then this method would look for saved state of batch 1000 * with revision (5 - 1) i.e. '1000_4.savepoint' * //from www. j a v a2s. c om * @param batchContext * The context for the batch * @throws BatchException * Any exception thrown during reading of the serialized file */ public static synchronized void updateBatchState(BatchContext batchContext) throws BatchException { BatchInfo newBatchInfo = batchContext.getBatchInfo(); String savepointFilePath = Configurations.getConfigurations().getConfigurations("CORE", "SAVEPOINT", "DIRECTORY"); String savePointFile = FilenameUtils.concat(savepointFilePath, newBatchInfo.getBatchNo() + "_" + (newBatchInfo.getBatchRevNo() - 1) + ".savepoint"); if (logger.isDebugEnabled()) { logger.debug("Reading the saved state from file : " + savePointFile); } FileInputStream fis = null; try { //Check whether the file exists File f = new File(savePointFile); if (!f.exists()) throw new BatchException("Cannot locate the the save point file named :" + savePointFile); fis = new FileInputStream(f); ObjectInputStream ois = new ObjectInputStream(fis); BatchInfo savedBatchInfo = (BatchInfo) ois.readObject(); newBatchInfo.setOrderedMap(savedBatchInfo.getOrderedMap()); newBatchInfo.setProgressLevelAtLastSavePoint( (ProgressLevel) savedBatchInfo.getProgressLevelAtLastSavePoint()); //This object is different but still cloned. newBatchInfo.setBatchRunDate(savedBatchInfo.getBatchRunDate()); newBatchInfo.setDateRun(savedBatchInfo.isDateRun()); if (logger.isDebugEnabled()) { logger.debug( "Last batch saved state is " + savedBatchInfo.getProgressLevelAtLastSavePoint().toString()); } //Set the ExecutionStatus in the ProgressLevel ExecutionStatus savedExecutionStatus = newBatchInfo.getProgressLevelAtLastSavePoint() .getExecutionStatus(); ProgressLevel.getProgressLevel(newBatchInfo.getBatchNo()) .setExecutionStatus(savedExecutionStatus.getEntity(), savedExecutionStatus.getStageCode()); fis.close(); fis = null; ois.close(); ois = null; } catch (FileNotFoundException e) { logger.error(e); throw new BatchException(e.getMessage(), e); } catch (IOException e) { logger.error(e); throw new BatchException(e.getMessage(), e); } catch (ClassNotFoundException e) { logger.error(e); throw new BatchException(e.getMessage(), e); } finally { if (fis != null) { try { fis.close(); } catch (IOException e) { } } } }
From source file:fusejext2.FuseJExt2.java
private static void setupBlockDevice() { try {//from w w w .j ava 2 s . c o m RandomAccessFile blockDevFile = new RandomAccessFile(filename, "rw"); blockDev = blockDevFile.getChannel(); } catch (FileNotFoundException e) { System.out.println("Can't open block device or file " + filename); System.out.println(e.getMessage()); System.exit(1); } }
From source file:edu.cornell.med.icb.goby.modes.AggregatePeaksByRPKMDifferenceMode.java
public static void writeRPKM(final String outputFileName, final ObjectList<AnnotationRPKM> annotationList, final boolean append) { PrintWriter writer = null;/* w w w. ja v a2 s. c o m*/ final File outputFile = new File(outputFileName); try { if (!outputFile.exists()) { writer = new PrintWriter(outputFile); // Write the file header writer.write( "Chromosome_Name\tStrand\tPrimary_ID\tSecondary_ID\tTranscript_Start\tTranscript_End\tAverage_RPKM\n"); } else { writer = new PrintWriter(new FileOutputStream(outputFile, append)); } final ObjectListIterator<AnnotationRPKM> annotIterator = annotationList.listIterator(); while (annotIterator.hasNext()) { final AnnotationRPKM annotation = annotIterator.next(); annotation.write(writer); } } catch (FileNotFoundException fnfe) { System.err.println("Caught exception in writeAnnotations: " + fnfe.getMessage()); System.exit(1); } finally { IOUtils.closeQuietly(writer); } }