public void usage1(String inputFile) throws FileNotFoundException { Velocity.init(); VelocityContext context = new VelocityContext(); context.put("author", "Elliot A."); context.put("address", "217 E Broadway"); context.put("phone", "555-1337"); FileInputStream file = new FileInputStream(inputFile); //Evaluate StringWriter swOut = new StringWriter(); Velocity.evaluate(context, swOut, "test", file); String result = swOut.getBuffer().toString(); System.out.println(result); }
private DecimalFormatSymbols readTestObject(File inputFile){ try (InputStream istream = inputFile.getName().endsWith(".txt") ? HexDumpReader.getStreamFromHexDump(inputFile) : new FileInputStream(inputFile)) { ObjectInputStream p = new ObjectInputStream(istream); DecimalFormatSymbols dfs = (DecimalFormatSymbols)p.readObject(); return dfs; } catch (Exception e) { errln("Test Malfunction in DFSSerialization: Exception while reading the object"); /* * logically should not throw this exception as errln throws exception * if not thrown yet - but in case errln got changed */ throw new RuntimeException("Test Malfunction: re-throwing the exception", e); } }
/** * 根据文件解码一个新nmap对象 * @param file * @return * @throws Exception */ public final NMap load(File file) throws Exception { if(file.exists()) { FileInputStream fis=new FileInputStream(file); BufferedInputStream bis=new BufferedInputStream(fis); ByteArrayOutputStream bos=new ByteArrayOutputStream();//定义一个内存输出流 int i=-1; while(true) { i=bis.read(); if(i==-1) { break; } bos.write(i);//保存到内存数组 } bos.flush(); bos.close(); bis.close(); return (NMap) decoder(bos.toByteArray()); } return null; }
/** * fsync OFF. * FileDescriptor#sync() should never be called. * @throws Exception . */ @Test public void testStoreTemporaryBarFile2() throws Exception { boolean fsyncEnabled = PersoniumUnitConfig.getFsyncEnabled(); PersoniumUnitConfig.set(BinaryData.FSYNC_ENABLED, "false"); try { CellEsImpl cell = new CellEsImpl(); cell.setId("hogeCell"); BarFileInstaller bfi = Mockito.spy(new BarFileInstaller(cell, "hogeBox", null, null)); Method method = BarFileInstaller.class.getDeclaredMethod( "storeTemporaryBarFile", new Class<?>[] {InputStream.class}); method.setAccessible(true); //any file method.invoke(bfi, new FileInputStream("pom.xml")); Mockito.verify(bfi, Mockito.never()).sync((FileDescriptor) Mockito.anyObject()); } finally { PersoniumUnitConfig.set(BinaryData.FSYNC_ENABLED, String.valueOf(fsyncEnabled)); } }
/** * Loads a resource and returns an InputStream to it. * * @param name * @return */ public static InputStream getAsStream(String name) { if (name == null) { return null; } try { URL url = getAsURL(name); if (url == null) { File file = new File(name); if (file.exists()) { return new FileInputStream(file); } return null; } else { return url.openStream(); } } catch (IOException e) { e.printStackTrace(); return null; } }
public static void copyFile(File sourceFile, File targetFile) throws IOException { // 新建文件输入流并对它进行缓冲 FileInputStream input = new FileInputStream(sourceFile); BufferedInputStream inBuff = new BufferedInputStream(input); // 新建文件输出流并对它进行缓冲 FileOutputStream output = new FileOutputStream(targetFile); BufferedOutputStream outBuff = new BufferedOutputStream(output); // 缓冲数组 byte[] b = new byte[1024 * 5]; int len; while ((len = inBuff.read(b)) != -1) { outBuff.write(b, 0, len); } // 刷新此缓冲的输出流 outBuff.flush(); //关闭流 inBuff.close(); outBuff.close(); output.close(); input.close(); }
public static String enfile_read(String file_name, byte[] key) throws Exception { file = new File(file_name); bufferedInputStream = new BufferedInputStream(new FileInputStream(file)); secretKey = new SecretKeySpec(key, "AES"); cipher = Cipher.getInstance(CIPHER_ALOGORTHM); cipher.init(Cipher.DECRYPT_MODE, secretKey); cipherInputStream = new CipherInputStream(bufferedInputStream, cipher); String str = ""; while((length = cipherInputStream.read(cache)) > 0) { str += new String(cache, 0, length); } return str; }
@Test public void testUpload() throws Exception { expectNew(org.apache.commons.net.ftp.FTPClient.class).andReturn(mockFtp); mockFtp.setConnectTimeout(DEFAULT_TIMEOUT); mockFtp.connect(HOSTNAME, PORT_NUMBER); mockFtp.setAutodetectUTF8(false); EasyMock.expectLastCall().once(); expect(mockFtp.login(USERNAME, PASSWORD)).andReturn(true); mockFtp.enterLocalPassiveMode(); expect(mockFtp.setFileType(org.apache.commons.net.ftp.FTPClient.BINARY_FILE_TYPE)).andReturn(true); expect(mockFtp.storeFile(eq(REMOTE_DIRECTORY_NAME + "/" + REMOTE_FILE_NAME), isA(FileInputStream.class))).andReturn(true); expect(mockFtp.getPassiveHost()).andReturn(HOSTNAME); replayAll(); testObject.connect(HOSTNAME, USERNAME, PASSWORD); testObject.uploadFile(LOCAL_FILE_NAME, REMOTE_DIRECTORY_NAME, REMOTE_FILE_NAME); verifyAll(); }
@Test @Ignore public void importBlocks() throws Exception { Logger logger = LoggerFactory.getLogger("VM"); logger.info("#######################################"); BlockchainImpl blockchain = createBlockchain(GenesisLoader.loadGenesis( getClass().getResourceAsStream("/genesis/frontier.json"))); Scanner scanner = new Scanner(new FileInputStream("D:\\ws\\ethereumj\\work\\blocks-rec.dmp")); while (scanner.hasNext()) { String blockHex = scanner.next(); Block block = new Block(Hex.decode(blockHex)); ImportResult result = blockchain.tryToConnect(block); if (result != ImportResult.EXIST && result != ImportResult.IMPORTED_BEST) { throw new RuntimeException(result + ": " + block + ""); } System.out.println("Imported " + block.getShortDescr()); } }
static boolean copyFileOntoRemovableStorage(Context context, Uri treeUri, String path, String destination) throws IOException { String mimeType = MediaType.getMimeType(path); DocumentFile file = DocumentFile.fromFile(new File(destination)); if (file.exists()) { int index = destination.lastIndexOf("."); destination = destination.substring(0, index) + " Copy" + destination.substring(index, destination.length()); } DocumentFile destinationFile = StorageUtil.createDocumentFile(context, treeUri, destination, mimeType); if (destinationFile != null) { ContentResolver resolver = context.getContentResolver(); OutputStream outputStream = resolver.openOutputStream(destinationFile.getUri()); InputStream inputStream = new FileInputStream(path); return writeStream(inputStream, outputStream); } return false; }
/** * Compare the data contents of two files. * * @param file1 the first file to compare * @param file2 the second file to compare * @return true if the files have the same content and length * @throws IOException if a java.io operation throws */ public boolean compareFiles(File file1, File file2) throws IOException { if (file1.length() != file2.length()) { return false; } InputStream in1 = new FileInputStream(file1); InputStream in2 = new FileInputStream(file2); for (;;) { int ch1 = in1.read(); if (ch1 == -1) { break; } int ch2 = in2.read(); if (ch1 != ch2) { in1.close(); in2.close(); return false; } } in1.close(); in2.close(); return true; }
private void addMappings(Map<String, Map<String, Object>> mappings, File mappingsDir) { File[] mappingsFiles = mappingsDir.listFiles(); for (File mappingFile : mappingsFiles) { if (mappingFile.isHidden()) { continue; } int lastDotIndex = mappingFile.getName().lastIndexOf('.'); String mappingType = lastDotIndex != -1 ? mappingFile.getName().substring(0, lastDotIndex) : mappingFile.getName(); try { String mappingSource = Streams.copyToString(new InputStreamReader(new FileInputStream(mappingFile), Charsets.UTF_8)); if (mappings.containsKey(mappingType)) { XContentHelper.mergeDefaults(mappings.get(mappingType), parseMapping(mappingSource)); } else { mappings.put(mappingType, parseMapping(mappingSource)); } } catch (Exception e) { logger.warn("failed to read / parse mapping [" + mappingType + "] from location [" + mappingFile + "], ignoring...", e); } } }
/** * @return null if we were unable to load the cached version */ public GrammaticalLabelSetImpl read() { // if we're tracking duplicated labels, we need to load the file directly in order to look at all the labels, so don't load from the cache if (this.language == LanguageProviderFactory.get().getBaseLanguage() && GrammaticalLabelFileParser.isDupeLabelTrackingEnabled()) { return null; } logger.info("Loading " + labelSetName + " from cache"); long start = System.currentTimeMillis(); try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(this.cacheFile))) { GrammaticalLabelSetImpl labelSet = (GrammaticalLabelSetImpl)ois.readObject(); logger.info("Loaded " + this.labelSetName + " from cache in " + (System.currentTimeMillis() - start) + " ms"); return labelSet; } catch (Exception e) { logger.log(Level.INFO, "Could not load " + labelSetName + " from cache: ", e); delete(); } return null; }
public final void restoreState(String slot) throws IOException, ClassNotFoundException{ if(!nsfplayer){ FileInputStream fin = new FileInputStream(slot); ObjectInputStream in = new ObjectInputStream(fin); pause = true; try { Thread.sleep(20); } catch (InterruptedException e) { e.printStackTrace(); } map = (Mapper) in.readObject(); map.apu = (APU) in.readObject(); map.cpu = (CPU_6502) in.readObject(); map.ppu = (ppu2C02) in.readObject(); map.setSystem(system); in.close(); pause = false; } }
private static Properties loadOptionProperties(IShaderPack sp) throws IOException { Properties properties = new Properties(); String s = shaderpacksdirname + "/" + sp.getName() + ".txt"; File file1 = new File(Minecraft.getMinecraft().mcDataDir, s); if (file1.exists() && file1.isFile() && file1.canRead()) { FileInputStream fileinputstream = new FileInputStream(file1); properties.load((InputStream)fileinputstream); fileinputstream.close(); return properties; } else { return properties; } }
public static void copyFile(File f1, File f2) throws Exception { if (!f2.getParentFile().exists()) { if (!f2.getParentFile().mkdirs()) { throw new Exception("Create file '" + f2.getName() + "' directory error !"); } } try { int length = 2097152; FileInputStream in = new FileInputStream(f1); FileOutputStream out = new FileOutputStream(f2); byte[] buffer = new byte[length]; while (true) { int ins = in.read(buffer); if (ins == -1) { in.close(); out.flush(); out.close(); } else out.write(buffer, 0, ins); } } catch (Exception e) { } }
/** * Reads the contents of a file in to a byte array. * * @param file file to read * @return the byte contents of the file * * @throws IOException throw if there is a problem reading the file in to the byte array */ public static byte[] fileToByteArray(File file) throws IOException { long numOfBytes = file.length(); if (numOfBytes > Integer.MAX_VALUE) { throw new IOException("File is to large to be read in to a byte array"); } byte[] bytes = new byte[(int) numOfBytes]; FileInputStream ins = new FileInputStream(file); int offset = 0; int numRead = 0; do { numRead = ins.read(bytes, offset, bytes.length - offset); offset += numRead; } while (offset < bytes.length && numRead >= 0); if (offset < bytes.length) { throw new IOException("Could not completely read file " + file.getName()); } ins.close(); return bytes; }
@SuppressWarnings("resource") public static void copyFile(File source, File target) throws IOException { if (!target.exists()) { target.createNewFile(); } FileChannel sourceChannel = null; FileChannel targetChannel = null; try { sourceChannel = new FileInputStream(source).getChannel(); targetChannel = new FileOutputStream(target).getChannel(); targetChannel.transferFrom(sourceChannel, 0L, sourceChannel.size()); } finally { if (sourceChannel != null) { sourceChannel.close(); } if (targetChannel != null) { targetChannel.close(); } } }
private void loadBook() { try { // 打开书籍 EpubReader reader = new EpubReader(); InputStream is = new FileInputStream(mFilePath); mBook = reader.readEpub(is); mTocReferences = (ArrayList<TOCReference>) mBook.getTableOfContents().getTocReferences(); mSpineReferences = mBook.getSpine().getSpineReferences(); setSpineReferenceTitle(); // 解压epub至缓存目录 FileUtils.unzipFile(mFilePath, Constant.PATH_EPUB + "/" + mFileName); } catch (IOException e) { e.printStackTrace(); } }
/** * Check if the CRC of the snapshot file matches the digest. * @param f The snapshot file object * @return The table list as a string * @throws IOException If CRC does not match */ public static String CRCCheck(File f) throws IOException { final FileInputStream fis = new FileInputStream(f); try { final BufferedInputStream bis = new BufferedInputStream(fis); ByteBuffer crcBuffer = ByteBuffer.allocate(4); if (4 != bis.read(crcBuffer.array())) { throw new EOFException("EOF while attempting to read CRC from snapshot digest"); } final int crc = crcBuffer.getInt(); final InputStreamReader isr = new InputStreamReader(bis, "UTF-8"); CharArrayWriter caw = new CharArrayWriter(); while (true) { int nextChar = isr.read(); if (nextChar == -1) { throw new EOFException("EOF while reading snapshot digest"); } if (nextChar == '\n') { break; } caw.write(nextChar); } String tableList = caw.toString(); byte tableListBytes[] = tableList.getBytes("UTF-8"); CRC32 tableListCRC = new CRC32(); tableListCRC.update(tableListBytes); tableListCRC.update("\n".getBytes("UTF-8")); final int calculatedValue = (int)tableListCRC.getValue(); if (crc != calculatedValue) { throw new IOException("CRC of snapshot digest did not match digest contents"); } return tableList; } finally { try { if (fis != null) fis.close(); } catch (IOException e) {} } }
public static byte[] readFile(File file) throws IOException { InputStream is = new FileInputStream(file); byte[] bytes = new byte[(int) file.length()]; try { int offset = 0; int numRead = 0; while (offset < bytes.length && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) { offset += numRead; } if (offset < bytes.length) { throw new IOException("Failed to completely read file '" + file.getName() + "'."); } } finally { is.close(); } return bytes; }
public static byte[] getBytesFromFile(File f) { if (f == null) { return null; } try { FileInputStream stream = new FileInputStream(f); ByteArrayOutputStream out = new ByteArrayOutputStream(1000); byte[] b = new byte[1000]; for (int n; (n = stream.read(b)) != -1; ) { out.write(b, 0, n); } stream.close(); out.close(); return out.toByteArray(); } catch (IOException e) { } return null; }
private static void pipeFileContents(File file, OutputStream pOut, int bufSize) throws IOException { FileInputStream in = new FileInputStream(file); byte[] buf = new byte[bufSize]; int len; while ((len = in.read(buf)) > 0) { //if user cancel the task break the pipe if(SharedData.IS_TASK_CANCELED){ throw new IOException("Operation Canceled"); } pOut.write(buf, 0, len); } pOut.close(); in.close(); }
private InputStream getResourceAsStream(String uri) throws FileNotFoundException { // Is uri absolute? if (uri.startsWith("file:")) { return new FileInputStream(new File(uri.substring(5))); } else { try { // see if file exists on the filesystem String real = ctxt.getRealPath(uri); if (real == null) { return ctxt.getResourceAsStream(uri); } else { return new FileInputStream(real); } } catch (FileNotFoundException ex) { // if file not found on filesystem, get the resource through // the context return ctxt.getResourceAsStream(uri); } } }
private static void addDirToZipArchive(ZipOutputStream zos, File fileToZip, String parrentDirectoryName) throws Exception { if (fileToZip == null || !fileToZip.exists()) { return; } String zipEntryName = fileToZip.getName(); if (parrentDirectoryName!=null && !parrentDirectoryName.isEmpty()) { zipEntryName = parrentDirectoryName + "/" + fileToZip.getName(); } if (fileToZip.isDirectory()) { for (File file : fileToZip.listFiles()) { addDirToZipArchive(zos, file, zipEntryName); } } else { byte[] buffer = new byte[1024]; FileInputStream fis = new FileInputStream(fileToZip); zos.putNextEntry(new ZipEntry(zipEntryName)); int length; while ((length = fis.read(buffer)) > 0) { zos.write(buffer, 0, length); } zos.closeEntry(); fis.close(); } }
public static void unjar(final Path targetDirectory, final Path sourceFile) { try (final FileInputStream fis = new FileInputStream(sourceFile.toFile()); final ZipInputStream jarInputStream = new ZipInputStream(fis)) { byte[] buffer = new byte[65536]; for (ZipEntry entry = jarInputStream.getNextEntry(); entry != null; entry = jarInputStream .getNextEntry()) { if (entry.isDirectory()) { targetDirectory.resolve(entry.getName()).toFile().mkdirs(); } else { // directory entries are optional targetDirectory.resolve(entry.getName()).getParent().toFile().mkdirs(); try (FileOutputStream fos = new FileOutputStream( targetDirectory.resolve(entry.getName()).toFile())) { for (int cnt = jarInputStream.read(buffer); cnt != -1; cnt = jarInputStream .read(buffer)) { fos.write(buffer, 0, cnt); } } } } } catch (IOException e) { LOGGER.error("Error in unjar", e); throw new IllegalStateException( "File was not uncompressed successfully", e); } }
/** * this function is used to read object from file. * * @return - return saved object from file */ public T readObject() { if (file.exists()) { try { //check whether file exists FileInputStream is = new FileInputStream(file); int size = is.available(); byte[] buffer = new byte[size]; is.read(buffer); is.close(); return new Gson().fromJson(new String(buffer), clazz); } catch (IOException e) { return null; } } return null; }
public RgxReader(String fileName, Charset charset, int _limit) throws FileNotFoundException { this(CharBuffer.allocate(1024)); fs = new FileInputStream(fileName); ReadableByteChannel channel = fs.getChannel(); CharsetDecoder decoder = charset.newDecoder(); reader = Channels.newReader(channel, decoder, -1); buf.limit(0); limit = _limit; }
public void unzip(String zipFile, String outputFolder){ byte[] buffer = new byte[1024]; try{ ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile)); ZipEntry ze = zis.getNextEntry(); while(ze!=null){ String fileName = ze.getName(); File newFile = new File(outputFolder + File.separator + fileName); System.out.println("file unzip : "+ newFile.getAbsoluteFile()); if (!newFile.exists()) { if (ze.isDirectory()) { newFile.mkdir(); } else { newFile.createNewFile(); FileOutputStream fos = new FileOutputStream(newFile); int len; while ((len = zis.read(buffer)) > 0) { fos.write(buffer, 0, len); } fos.close(); } } ze = zis.getNextEntry(); } zis.closeEntry(); zis.close(); } catch(Exception ex) { displayErrorMessage("Error", "Unable to load the project", ex); } }
public InputStream openInputStreamElement(String streamName) throws IOException { try { return new FileInputStream(new File(streamName)); } catch (Throwable e) { throw JavaSystem.toIOException(e); } }
public static void main(String[] args) throws IOException, RecognitionException { String path = args[0]; String pkg = args[1]; String stem = args[2]; FileInputStream stream = new FileInputStream(path + File.separatorChar + stem + ".yapg"); ANTLRInputStream antlr = new ANTLRInputStream(stream); GrammarLexer lexer = new GrammarLexer(antlr); CommonTokenStream tokens = new CommonTokenStream(lexer); GrammarParser parser = new GrammarParser(tokens); Grammar g = parser.parseGrammar(); if (parser.error) throw new RecognitionException(); Generator.generate(path, pkg, stem, g); }
static void checkFileData(File file, String expected) throws Exception { FileInputStream fis = new FileInputStream(file); Reader r = new BufferedReader(new InputStreamReader(fis, "ASCII")); StringBuilder sb = new StringBuilder(); int c; while ((c = r.read()) != -1) sb.append((char)c); String contents = sb.toString(); if (! contents.equals(expected)) throw new Exception("expected: " + expected + ", got: " + contents); r.close(); }
protected byte[] getClassFileBytes(String className) { byte result[] = null; if(m_bCanLoadClass) { String clpack = className.replace('.', '/') ; for(int n=0; n<m_arrPaths.size(); n++) { String csPath = m_arrPaths.get(n); try { FileInputStream fi = new FileInputStream(csPath + clpack + ".class"); result = new byte[fi.available()]; fi.read(result); fi.close() ; return result; } catch (Exception e) { } } } if(m_bCanLoadJar && m_jarEntries != null) { result = m_jarEntries.loadJarEntry(className); } return result; }
public static void copyFile(File sourceFile, File targetFile) { try { byte[] bytes = readFully(new FileInputStream(sourceFile)); FileOutputStream out = new FileOutputStream(targetFile); out.write(bytes); out.close(); } catch (IOException e) { throw new IllegalArgumentException(e); } }
public static Object deserialize(String path) throws IOException, ClassNotFoundException { try ( ObjectInputStream ois = new ObjectInputStream(new FileInputStream(path)) ) { return ois.readObject(); } }
private <E> E readTable(String key, File originalFile, boolean v1CompatibilityMode) { try { final Input i = new Input(new FileInputStream(originalFile)); final Kryo kryo = getKryo(); if (v1CompatibilityMode) { kryo.getFieldSerializerConfig().setOptimizedGenerics(true); } final RakTable<E> paperTable = kryo.readObject(i, RakTable.class); i.close(); if (v1CompatibilityMode) { kryo.getFieldSerializerConfig().setOptimizedGenerics(false); } return paperTable.content; } catch (FileNotFoundException | KryoException | ClassCastException e) { if (!v1CompatibilityMode) { return readTable(key, originalFile, true); } if (originalFile.exists()) { if (!originalFile.delete()) { throw new RuntimeException("cant deleted file " + originalFile, e); } } String errorMessage = "cant read file " + originalFile + " for table " + key; throw new RuntimeException(errorMessage, e); } }
@SuppressWarnings("ResultOfMethodCallIgnored") public AntiTowerListener(JavaPlugin plugin) { File file = new File("world/tops.dat"); if (file.exists()) { try { int length = (int)Math.sqrt(file.length()); this.data = new byte[length][length]; FileInputStream inputStream = new FileInputStream(file); byte buffer[] = new byte[1]; int x = 0; int z = 0; while (inputStream.read(buffer) == 1) { this.data[x][z] = buffer[0]; z++; if (z == length) { z = 0; x++; } } inputStream.close(); plugin.getServer().getPluginManager().registerEvents(this, plugin); } catch (Exception exception) { plugin.getLogger().log(Level.SEVERE, "Can't load AntiTower, disabling it.", exception); } } }
protected InputStream getStreamFromFile(String imageUri, Object extra) throws IOException { String filePath = Scheme.FILE.crop(imageUri); if (isVideoFileUri(imageUri)) { return getVideoThumbnailStream(filePath); } return new ContentLengthInputStream(new BufferedInputStream(new FileInputStream(filePath) , 32768), (int) new File(filePath).length()); }
@Test public void test() { try { Transformer transformer = TransformerFactory.newInstance().newTransformer(); copyDTDtoWorkDir(); File outf = new File(USER_DIR + "Bug4693341.out"); StreamResult result = new StreamResult(new FileOutputStream(outf)); String in = getClass().getResource("Bug4693341.xml").getPath(); File file = new File(in); StreamSource source = new StreamSource(new FileInputStream(file), ("file://" + in)); transformer.transform(source, result); //URL inputsource = new URL("file", "", golden); URL output = new URL("file", "", outf.getPath()); // error happens when trying to parse output String systemId = output.toExternalForm(); System.out.println("systemId: " + systemId); InputSource is = new InputSource(systemId); SAXParser parser = SAXParserFactory.newInstance().newSAXParser(); parser.parse(is, new DefaultHandler()); } catch (Exception ex) { Assert.fail(ex.getMessage()); } }
/** * Tests inserting blob data as a stream * * @throws Exception * if an error occurs */ private void testByteStreamInsert(Connection c) throws Exception { BufferedInputStream bIn = new BufferedInputStream(new FileInputStream(testBlobFile)); this.pstmt = c.prepareStatement("INSERT INTO BLOBTEST(blobdata) VALUES (?)"); this.pstmt.setBinaryStream(1, bIn, (int) testBlobFile.length()); this.pstmt.execute(); this.pstmt.clearParameters(); doRetrieval(); }