Here are the examples of the java api class java.io.FileInputStream taken from open source projects.
1. JcaPKIXIdentityBuilder#build()
Project: bc-java
File: JcaPKIXIdentityBuilder.java
File: JcaPKIXIdentityBuilder.java
/** * Build an identity from the passed in key and certificate file in PEM format. * * @param keyFile the PEM file containing the key * @param certificateFile the PEM file containing the certificate * @return an identity object. * @throws IOException on a general parsing error. * @throws CertificateException on a certificate parsing error. */ public JcaPKIXIdentity build(File keyFile, File certificateFile) throws IOException, CertificateException { checkFile(keyFile); checkFile(certificateFile); FileInputStream keyStream = new FileInputStream(keyFile); FileInputStream certificateStream = new FileInputStream(certificateFile); JcaPKIXIdentity rv = build(keyStream, certificateStream); keyStream.close(); certificateStream.close(); return rv; }
2. Cluster#readClusters()
Project: LIRE
File: Cluster.java
File: Cluster.java
// TODO: re-visit here to make the length variable (depending on the actual feature size). public static Cluster[] readClusters(String file) throws IOException { FileInputStream fin = new FileInputStream(file); byte[] tmp = new byte[4]; fin.read(tmp, 0, 4); Cluster[] result = new Cluster[SerializationUtils.toInt(tmp)]; fin.read(tmp, 0, 4); int size = SerializationUtils.toInt(tmp); tmp = new byte[size * 8]; int bytesRead; for (int i = 0; i < result.length; i++) { bytesRead = fin.read(tmp, 0, size * 8); if (bytesRead != size * 8) System.err.println("Didn't read enough bytes ..."); result[i] = new Cluster(); result[i].setByteRepresentation(tmp); } fin.close(); return result; }
3. XMLoader#loadImageXMM()
Project: XM-File-Format
File: XMLoader.java
File: XMLoader.java
/* * loads data from file location and many images are generated, stored as a Mipmap object * * @param location file to be loaded in * * @return Mipmap generated */ public static Mipmap loadImageXMM(File location) throws IOException { final FileInputStream fis = new FileInputStream(location); final byte[] header = new byte[2]; fis.read(header); final byte[] sizes = new byte[header[1] * 2 * 2]; fis.read(sizes); final Image[] images = new Image[header[1]]; for (int i = 0; i < header[1]; i++) { final boolean transparency = fis.read() == 1; final int width = (sizes[i * 4 + 1] & 0xFF) << 8 | (sizes[i * 4] & 0xFF), height = (sizes[i * 4 + 3] & 0xFF) << 8 | (sizes[i * 4 + 2] & 0xFF); final byte[] body = new byte[width * height * 4]; fis.read(body); images[i] = new Image(width, height, transparency, body); } fis.close(); return new Mipmap(header[0] == 1, images); }
4. XMLoader#loadImageXMI()
Project: XM-File-Format
File: XMLoader.java
File: XMLoader.java
/* * loads data from file location and an image is generated * * @param location file to be loaded in * * @return Image generated */ public static Image loadImageXMI(File location) throws IOException { final FileInputStream fis = new FileInputStream(location); final byte[] header = new byte[5]; fis.read(header); final boolean transparency = header[0] == 1; final int width = (header[2] & 0xFF) << 8 | (header[1] & 0xFF), height = (header[4] & 0xFF) << 8 | (header[3] & 0xFF); final byte[] body = new byte[width * height * 4]; fis.read(body); fis.close(); return new Image(width, height, transparency, body); }
5. XMPacker#unpack()
Project: XM-File-Format
File: XMPacker.java
File: XMPacker.java
/* * Given that the source points to an XMP file, source is deflated into a temp file. The temp file * is read and each entry will be unpacked into new files in root destination. * * @param source * @param destination * */ public static void unpack(File source, File destination) throws IOException { final File vtemp = File.createTempFile("xmp_gen" + System.currentTimeMillis(), ".tmp"); vtemp.createNewFile(); Zipper.unzip(source, vtemp, true); byte[] one = new byte[4]; final FileInputStream sfis = new FileInputStream(vtemp); sfis.read(one); final int files = byteToInt(one); final byte[] lenheader = new byte[files * 8]; sfis.read(lenheader); final int[] lenints = byteRangeToInt(lenheader); for (int i = 0; i < files; i++) { final byte[] name = new byte[lenints[i * 2 + 1]], fbytes = new byte[lenints[i * 2]]; final File out = new File(destination, new String(name)); final FileOutputStream xmpfos = new FileOutputStream(out); xmpfos.write(fbytes); xmpfos.flush(); xmpfos.close(); } sfis.close(); vtemp.delete(); }
6. AvlTreePerfTest#testAVLTreeDeserializationPerf()
Project: directory-server
File: AvlTreePerfTest.java
File: AvlTreePerfTest.java
@Test @Ignore public void testAVLTreeDeserializationPerf() throws Exception { FileInputStream fin = new FileInputStream(treeSerialFile); byte data[] = new byte[(int) treeSerialFile.length()]; start = System.nanoTime(); fin.read(data); tree = (AvlTree<Integer>) treeMarshaller.deserialize(data); end = System.nanoTime(); System.out.println("total time taken for reconstructing a serialized AVLTree ->" + getTime(start, end)); fin.close(); }
7. FileAppenderTest#verifyFile()
Project: logging-log4j2
File: FileAppenderTest.java
File: FileAppenderTest.java
private void verifyFile(final int count) throws Exception { // String expected = "[\\w]* \\[\\s*\\] INFO TestLogger - Test$"; final String expected = "^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2},\\d{3} \\[[^\\]]*\\] INFO TestLogger - Test"; final Pattern pattern = Pattern.compile(expected); final FileInputStream fis = new FileInputStream(FILENAME); final BufferedReader is = new BufferedReader(new InputStreamReader(fis)); int counter = 0; String str = Strings.EMPTY; while (is.ready()) { str = is.readLine(); // System.out.println(str); ++counter; final Matcher matcher = pattern.matcher(str); assertTrue("Bad data: " + str, matcher.matches()); } fis.close(); assertTrue("Incorrect count: was " + counter + " should be " + count, count == counter); fis.close(); }
8. TestJenaReaderRIOT#jenaread_stream()
Project: jena
File: TestJenaReaderRIOT.java
File: TestJenaReaderRIOT.java
private static void jenaread_stream(String filename, String lang) throws IOException { filename = filename(filename); // Read with a base try (FileInputStream in0 = new FileInputStream(filename)) { Model m0 = ModelFactory.createDefaultModel(); RDFDataMgr.read(m0, in0, "http://example/base2", RDFLanguages.nameToLang(lang)); } // Read again, but without base try (FileInputStream in1 = new FileInputStream(filename)) { Model m1 = ModelFactory.createDefaultModel(); RDFDataMgr.read(m1, in1, RDFLanguages.nameToLang(lang)); } // Read via Jena API. Model m2 = ModelFactory.createDefaultModel(); try (FileInputStream in2 = new FileInputStream(filename)) { m2.read(in2, "http://example/base3", lang); } String x = FileUtils.readWholeFileAsUTF8(filename); Model m3 = ModelFactory.createDefaultModel(); m2.read(new StringReader(x), "http://example/base4", lang); }
9. FileIOStreamT#main()
Project: java-core-learning-example
File: FileIOStreamT.java
File: FileIOStreamT.java
public static void main(String[] args) throws IOException { // ??????? FileInputStream fileInputStream = new FileInputStream(thisFilePath); // ??????? FileOutputStream fileOutputStream = new FileOutputStream("data.txt"); // ?????????? byte[] inOutBytes = new byte[fileInputStream.available()]; // ????????????inOutBytes?? fileInputStream.read(inOutBytes); // ?inOutBytes??????data.txt??? fileOutputStream.write(inOutBytes); fileOutputStream.close(); fileInputStream.close(); }
10. RandomAccessFileTest#test_write$BII()
Project: j2objc
File: RandomAccessFileTest.java
File: RandomAccessFileTest.java
/** * java.io.RandomAccessFile#write(byte[], int, int) */ public void test_write$BII() throws IOException { // Test for method void java.io.RandomAccessFile.write(byte [], int, // int) RandomAccessFile raf = new java.io.RandomAccessFile(fileName, "rw"); byte[] rbuf = new byte[4000]; raf.write(fileString.getBytes(), 0, fileString.length()); raf.close(); FileInputStream fis = new java.io.FileInputStream(fileName); fis.read(rbuf, 0, fileString.length()); assertEquals("Incorrect bytes written", fileString, new String(rbuf, 0, fileString.length())); fis.close(); }
11. APPIOSApplication#getFormat()
Project: ios-driver
File: APPIOSApplication.java
File: APPIOSApplication.java
private PListFormat getFormat(File f) throws IOException { FileInputStream fis = new FileInputStream(f); byte b[] = new byte[8]; fis.read(b, 0, 8); String magicString = new String(b); fis.close(); if (magicString.startsWith("bplist")) { return PListFormat.binary; } else if (magicString.trim().startsWith("(") || magicString.trim().startsWith("{") || magicString.trim().startsWith("/")) { return PListFormat.text; } else { return PListFormat.xml; } }
12. TestSiddhiStateSnapshotAndRestore#testSimpleSiddhiQuery()
Project: incubator-eagle
File: TestSiddhiStateSnapshotAndRestore.java
File: TestSiddhiStateSnapshotAndRestore.java
@Test public void testSimpleSiddhiQuery() throws Exception { String tmpdir = System.getProperty("java.io.tmpdir"); System.out.println("temporary directory: " + tmpdir); String stateFile = tmpdir + "/siddhi-state"; ExecutionPlanRuntime executionPlanRuntime = setupRuntimeForSimple(); executionPlanRuntime.getInputHandler("testStream").send(new Object[] { "rename", "/tmp/pii" }); byte[] state = executionPlanRuntime.snapshot(); int length = state.length; FileOutputStream output = new FileOutputStream(stateFile); output.write(state); output.close(); executionPlanRuntime.shutdown(); ExecutionPlanRuntime restoredRuntime = setupRuntimeForSimple(); FileInputStream input = new FileInputStream(stateFile); byte[] restoredState = new byte[length]; input.read(restoredState); restoredRuntime.restore(restoredState); restoredRuntime.getInputHandler("testStream").send(new Object[] { "rename", "/tmp/pii" }); input.close(); restoredRuntime.shutdown(); }
13. ThumbnailatorTest#testCreateThumbnail_IOII_Bmp()
Project: thumbnailator
File: ThumbnailatorTest.java
File: ThumbnailatorTest.java
/** * Test for * {@link Thumbnailator#createThumbnail(InputStream, OutputStream, int, int)} * where, * * 1) Method arguments are correct * 2) Input data is a BMP image * * Expected outcome is, * * 1) Processing will complete successfully. * * @throws IOException */ @Test public void testCreateThumbnail_IOII_Bmp() throws IOException { /* * Actual test */ byte[] bytes = new byte[40054]; FileInputStream fis = new FileInputStream("src/test/resources/Thumbnailator/grid.bmp"); fis.read(bytes); fis.close(); InputStream is = new ByteArrayInputStream(bytes); ByteArrayOutputStream os = new ByteArrayOutputStream(); Thumbnailator.createThumbnail(is, os, 50, 50); /* * Post-test checks */ InputStream thumbIs = new ByteArrayInputStream(os.toByteArray()); BufferedImage thumb = ImageIO.read(thumbIs); assertEquals(50, thumb.getWidth()); assertEquals(50, thumb.getHeight()); }
14. ScreenshotTest#digest()
Project: operaprestodriver
File: ScreenshotTest.java
File: ScreenshotTest.java
private static int digest(String filename) throws IOException { FileInputStream fis = new FileInputStream(filename); byte[] data = new byte[fis.available()]; int i = 0; int c; while ((c = fis.read()) != -1) { data[i++] = (byte) c; } fis.close(); final Adler32 digester = new Adler32(); digester.update(data); return (int) digester.getValue(); }
15. SynonymMap#loadFromFile()
Project: opensearchserver
File: SynonymMap.java
File: SynonymMap.java
private void loadFromFile(File file) throws FileNotFoundException, IOException { FileInputStream fis = new FileInputStream(file); InputStreamReader isr = new InputStreamReader(fis, "UTF-8"); BufferedReader br = new BufferedReader(isr); String line; while ((line = br.readLine()) != null) { String[] terms = splitTerms(line); for (String key : terms) expressionMap.add(key, terms); size++; } br.close(); isr.close(); fis.close(); }
16. TestLibrary#copyFile()
Project: openjdk
File: TestLibrary.java
File: TestLibrary.java
public static void copyFile(File srcFile, File dstFile) throws IOException { FileInputStream src = new FileInputStream(srcFile); FileOutputStream dst = new FileOutputStream(dstFile); byte[] buf = new byte[32768]; while (true) { int count = src.read(buf); if (count < 0) { break; } dst.write(buf, 0, count); } dst.close(); src.close(); }
17. CmsSetupTestSimapi#readFile()
Project: opencms-core
File: CmsSetupTestSimapi.java
File: CmsSetupTestSimapi.java
private byte[] readFile(File file) throws IOException { // create input and output stream FileInputStream in = new FileInputStream(file); ByteArrayOutputStream out = new ByteArrayOutputStream(); // read the file content int c; while ((c = in.read()) != -1) { out.write(c); } in.close(); out.close(); return out.toByteArray(); }
18. CmsFileUtil#copy()
Project: opencms-core
File: CmsFileUtil.java
File: CmsFileUtil.java
/** * Simply version of a 1:1 binary file copy.<p> * * @param fromFile the name of the file to copy * @param toFile the name of the target file * @throws IOException if any IO error occurs during the copy operation */ public static void copy(String fromFile, String toFile) throws IOException { File inputFile = new File(fromFile); File outputFile = new File(toFile); if (!outputFile.getParentFile().isDirectory()) { outputFile.getParentFile().mkdirs(); } FileInputStream in = new FileInputStream(inputFile); FileOutputStream out = new FileOutputStream(outputFile); // transfer bytes from in to out byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } in.close(); out.close(); }
19. ProductZipWriter#writeTo()
Project: oodt
File: ProductZipWriter.java
File: ProductZipWriter.java
@Override public void writeTo(ProductResource resource, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { // Create a zip file for the product resource. File zipFile = new ProductZipper().createZipFile(resource); // Add the zip file to the HTTP response entity stream. httpHeaders.add("Content-Type", "application/zip"); httpHeaders.add("Content-Disposition", "attachment; filename=\"" + zipFile.getName() + "\""); FileInputStream fis = new FileInputStream(zipFile); IOUtils.copy(fis, entityStream); fis.close(); }
20. DatasetZipWriter#writeTo()
Project: oodt
File: DatasetZipWriter.java
File: DatasetZipWriter.java
@Override public void writeTo(DatasetResource resource, Class<?> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream) throws IOException, WebApplicationException { // Create a zip file for the dataset resource. File zipFile = new DatasetZipper().createZipFile(resource); // Add the zip file to the HTTP response entity stream. httpHeaders.add("Content-Type", "application/zip"); httpHeaders.add("Content-Disposition", "attachment; filename=\"" + zipFile.getName() + "\""); FileInputStream fis = new FileInputStream(zipFile); IOUtils.copy(fis, entityStream); fis.close(); }
21. RssConfiguration#initialize()
Project: oodt
File: RssConfiguration.java
File: RssConfiguration.java
/** * Initializes the parameters in the configuration object using values from * the supplied file. * @param file the configuration file * @throws IOException if the file does not exist and cannot be read */ public void initialize(File file) throws IOException { FileInputStream fis = new FileInputStream(file); Document document = XMLUtils.getDocumentRoot(fis); Element root = document.getDocumentElement(); channelLink = root.getAttribute(CHANNEL_LINK); namespaceList = readNamespaces(root); tagList = readTags(root); fis.close(); }
22. MKVDemuxerTest#setUp()
Project: jcodec
File: MKVDemuxerTest.java
File: MKVDemuxerTest.java
@Before public void setUp() throws IOException { FileInputStream inputStream = new FileInputStream("./src/test/resources/mkv/10frames.webm"); par = new MKVParser(new FileChannelWrapper(inputStream.getChannel())); List<EbmlMaster> t = null; try { t = par.parse(); } finally { closeQuietly(inputStream); } demInputStream = new FileInputStream("./src/test/resources/mkv/10frames.webm"); dem = new MKVDemuxer(t, new FileChannelWrapper(demInputStream.getChannel())); }
23. CopyFileT#copyFile()
Project: java-core-learning-example
File: CopyFileT.java
File: CopyFileT.java
public static void copyFile(File srcFile, File destFile) throws IOException { // ????? if (!srcFile.exists()) { throw new IllegalArgumentException("???" + srcFile + "???"); } // ???????? if (!srcFile.isFile()) { throw new IllegalArgumentException(srcFile + "????"); } FileInputStream in = new FileInputStream(srcFile); FileOutputStream out = new FileOutputStream(destFile); byte[] bytes = new byte[2 * 1024]; int b; while ((b = in.read(bytes, 0, bytes.length)) != -1) { out.write(bytes, 0, b); out.flush(); } out.close(); in.close(); }
24. AnsiConsoleExample2#main()
Project: jansi
File: AnsiConsoleExample2.java
File: AnsiConsoleExample2.java
public static void main(String[] args) throws IOException { String file = "src/test/resources/jansi.ans"; if (args.length > 0) file = args[0]; // Allows us to disable ANSI processing. if ("true".equals(System.getProperty("jansi", "true"))) { AnsiConsole.systemInstall(); } System.out.print(ansi().reset().eraseScreen().cursor(1, 1)); System.out.print("======================================================================="); FileInputStream f = new FileInputStream(file); int c; while ((c = f.read()) >= 0) { System.out.write(c); } f.close(); System.out.println("======================================================================="); }
25. AnsiConsoleExample#main()
Project: jansi
File: AnsiConsoleExample.java
File: AnsiConsoleExample.java
public static void main(String[] args) throws IOException { String file = "src/test/resources/jansi.ans"; if (args.length > 0) file = args[0]; // Allows us to disable ANSI processing. if ("true".equals(System.getProperty("jansi", "true"))) { AnsiConsole.systemInstall(); } FileInputStream f = new FileInputStream(file); int c; while ((c = f.read()) >= 0) { System.out.write(c); } f.close(); }
26. AbstractApplication#loadConfig()
Project: jackrabbit-filevault
File: AbstractApplication.java
File: AbstractApplication.java
public void loadConfig(String path) throws IOException { File file = new File(path == null ? DEFAULT_CONF_FILENAME : path); if (!file.canRead() && path == null) { // ignore errors for default config return; } Properties props = new Properties(); FileInputStream in = new FileInputStream(file); props.load(in); in.close(); Iterator iter = globalEnv.keySet().iterator(); while (iter.hasNext()) { String key = (String) iter.next(); if (!props.containsKey(key)) { props.put(key, globalEnv.getProperty(key)); } } globalEnv = props; log.info("Configuration loaded from {}", file.getCanonicalPath()); }
27. OldFileChannelTest#test_forceZ()
Project: j2objc
File: OldFileChannelTest.java
File: OldFileChannelTest.java
public void test_forceZ() throws Exception { ByteBuffer writeBuffer = ByteBuffer.wrap(CONTENT_AS_BYTES); writeOnlyFileChannel.write(writeBuffer); writeOnlyFileChannel.force(true); byte[] readBuffer = new byte[CONTENT_AS_BYTES_LENGTH]; fis = new FileInputStream(fileOfWriteOnlyFileChannel); fis.read(readBuffer); assertTrue(Arrays.equals(CONTENT_AS_BYTES, readBuffer)); writeOnlyFileChannel.write(writeBuffer); writeOnlyFileChannel.force(false); fis.close(); readBuffer = new byte[CONTENT_AS_BYTES_LENGTH]; fis = new FileInputStream(fileOfWriteOnlyFileChannel); fis.read(readBuffer); assertTrue(Arrays.equals(CONTENT_AS_BYTES, readBuffer)); fis.close(); }
28. TestIO#testCustomTypesIO()
Project: hadoop-mapreduce
File: TestIO.java
File: TestIO.java
public void testCustomTypesIO() throws IOException { byte[] rawBytes = new byte[] { 100, 0, 0, 0, 3, 1, 2, 3 }; FileOutputStream ostream = new FileOutputStream(tmpfile); DataOutputStream dostream = new DataOutputStream(ostream); TypedBytesOutput out = new TypedBytesOutput(dostream); out.writeRaw(rawBytes); dostream.close(); ostream.close(); FileInputStream istream = new FileInputStream(tmpfile); DataInputStream distream = new DataInputStream(istream); TypedBytesInput in = new TypedBytesInput(distream); assertTrue(Arrays.equals(rawBytes, in.readRaw())); distream.close(); istream.close(); }
29. Storage#openScore()
Project: music-synthesizer-for-android
File: Storage.java
File: Storage.java
/** * Opens the score with the given name. The name should be name of a valid score file in storage. * The file must be in the root external files directory for the app. * * @param score - The mutable score to update with the data from storage. * @param name - The name of the file, minus the ".pb" extension. * @param context - The Android application context. */ public static void openScore(Score.Builder score, String name, Context context) throws IOException { if (!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) && !Environment.MEDIA_MOUNTED_READ_ONLY.equals(Environment.getExternalStorageState())) { throw new IOException("External storage is not readable."); } File path = context.getExternalFilesDir(null); File file = new File(path, name + ".pb"); FileInputStream in = new FileInputStream(file); score.clear(); score.mergeFrom(in); in.close(); }
30. DataTypeTranslater#fileToByte()
Project: MiniWeChat-Server
File: DataTypeTranslater.java
File: DataTypeTranslater.java
/** * ???Byte[] * @param address * @return * @throws IOException */ public static byte[] fileToByte(String address) throws IOException { // System.err.println("FilePath : " + address); File file = new File(address); long fileSize = file.length(); FileInputStream fi = new FileInputStream(file); byte[] buffer = new byte[(int) fileSize]; int offset = 0; int numRead = 0; while (offset < buffer.length && (numRead = fi.read(buffer, offset, buffer.length - offset)) >= 0) { offset += numRead; } // ???????? if (offset != buffer.length) { throw new IOException("Could not completely read file " + file.getName()); } fi.close(); return buffer; }
31. UnicodeWriterTest#test()
Project: metamodel
File: UnicodeWriterTest.java
File: UnicodeWriterTest.java
@Test public void test() throws IOException { File file = new File("target/unicodeWriterTest.txt"); Writer writer = new UnicodeWriter(file, "UTF-8"); writer.write("Hello"); writer.close(); FileInputStream is = new FileInputStream(file); byte[] bytes = new byte[100]; assertEquals(8, is.read(bytes)); assertEquals(UnicodeWriter.UTF8_BOM[0], bytes[0]); assertEquals(UnicodeWriter.UTF8_BOM[1], bytes[1]); assertEquals(UnicodeWriter.UTF8_BOM[2], bytes[2]); assertEquals((byte) 'H', bytes[3]); is.close(); }
32. ZipLibrary#zipFile()
Project: mcMMO
File: ZipLibrary.java
File: ZipLibrary.java
private static void zipFile(ZipOutputStream zos, String path, File file) throws IOException { if (!file.canRead()) { mcMMO.p.getLogger().severe("Cannot read " + file.getCanonicalPath() + "(File Permissions?)"); return; } zos.putNextEntry(new ZipEntry(buildPath(path, file.getName()))); FileInputStream fis = new FileInputStream(file); byte[] buffer = new byte[4092]; int byteCount; while ((byteCount = fis.read(buffer)) != -1) { zos.write(buffer, 0, byteCount); } fis.close(); zos.closeEntry(); }
33. FileStoreClient#getFileContent()
Project: linkbinder
File: FileStoreClient.java
File: FileStoreClient.java
/** * fileId?????????????????????????. * ??????????????????????. * ???????????????????. * * @param fileId ????ID * @param filePath?????? * @return ???????????? * @throws FileStoreException ???????????? */ public byte[] getFileContent(String fileId, String filePath) throws FileStoreException { ArgumentValidator.validateNotEmpty(fileId); ArgumentValidator.validateNotEmpty(filePath); File source = getFile(fileId); File dest = new File(filePath); // ?? try (FileInputStream in = new FileInputStream(source); FileOutputStream out = new FileOutputStream(dest)) { IOUtils.copy(in, out); } catch (IOException e) { throw new FileStoreException(e); } // ??????? try (FileInputStream in = new FileInputStream(dest)) { return IOUtils.toByteArray(in); } catch (IOException e) { throw new FileStoreException(e); } }
34. FileIO#copyFile()
Project: librec
File: FileIO.java
File: FileIO.java
public static void copyFile(File source, File target) throws Exception { FileInputStream fis = new FileInputStream(source); FileOutputStream fos = new FileOutputStream(target); FileChannel inChannel = fis.getChannel(); FileChannel outChannel = fos.getChannel(); int maxCount = (64 * 1024 * 1024) - (32 * 1024); long size = inChannel.size(); long position = 0; while (position < size) { position += inChannel.transferTo(position, maxCount, outChannel); } inChannel.close(); outChannel.close(); fis.close(); fos.close(); }
35. JarFileCopy#toCopy()
Project: LGame
File: JarFileCopy.java
File: JarFileCopy.java
private void toCopy(File src, File target) throws IOException { target.getParentFile().mkdirs(); if (prj.projects.verbose) { Log.log("[Info]" + prj.name + ":copy " + src.getCanonicalPath() + " -> " + target.getCanonicalPath()); } FileOutputStream out = new FileOutputStream(target); FileInputStream in = new FileInputStream(src); long size = copy(in, out); prj.projects.totalCopys += size; in.close(); out.close(); target.setLastModified(src.lastModified()); count++; }
36. Grep#containsPattern()
Project: lenya
File: Grep.java
File: Grep.java
/** * Check if the given file contains the pattern * * @param file the file which is to be searched for the pattern * @param pattern the pattern that is being searched. * * @return true if the file contains the string, false otherwise. * * @throws IOException */ public static boolean containsPattern(File file, Pattern pattern) throws IOException { // Open the file and then get a channel from the stream FileInputStream fis = new FileInputStream(file); FileChannel fc = fis.getChannel(); // Get the file's size and then map it into memory int sz = (int) fc.size(); MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, sz); // Decode the file into a char buffer CharBuffer cb = decoder.decode(bb); // Perform the search // Pattern matcher Matcher pm = pattern.matcher(cb); boolean result = pm.find(); // Close the channel and the stream fc.close(); fis.close(); return result; }
37. ReTokenizeFile#readFile()
Project: lenya
File: ReTokenizeFile.java
File: ReTokenizeFile.java
/** * reads a file in the specified encoding. * @param file the file to read. * @param encoding the file encoding * @return the content of the file. * @throws FileNotFoundException if the file does not exists. * @throws IOException if something else went wrong. */ protected String readFile(File file, Charset charset) throws FileNotFoundException, IOException { FileInputStream inputFile = new FileInputStream(file); InputStreamReader inputStream; if (charset != null) { inputStream = new InputStreamReader(inputFile, charset); } else { inputStream = new InputStreamReader(inputFile); } BufferedReader bufferReader = new BufferedReader(inputStream); StringBuffer buffer = new StringBuffer(); String line = ""; while (bufferReader.ready()) { line = bufferReader.readLine(); buffer.append(line); } bufferReader.close(); inputStream.close(); inputFile.close(); return buffer.toString(); }
38. InvertedIndexLocalTest#setUp()
Project: kylin
File: InvertedIndexLocalTest.java
File: InvertedIndexLocalTest.java
@Before public void setUp() throws Exception { this.createTestMetadata(); this.ii = IIManager.getInstance(getTestConfig()).getII("test_kylin_ii_left_join"); File file = new File(LOCALMETA_TEST_DATA, "data/flatten_data_for_ii.csv"); FileInputStream in = new FileInputStream(file); this.lines = IOUtils.readLines(in, "UTF-8"); in.close(); dictionaryMap = buildDictionary(Lists.transform(lines, new Function<String, List<String>>() { @Nullable @Override public List<String> apply(@Nullable String input) { return Lists.newArrayList(input.split(",")); } }), ii.getDescriptor()); this.info = new TableRecordInfo(ii.getDescriptor(), dictionaryMap); }
39. TestCopyCommandClusterSchemaEvolution#createDestination()
Project: kite
File: TestCopyCommandClusterSchemaEvolution.java
File: TestCopyCommandClusterSchemaEvolution.java
@Override public void createDestination() throws Exception { FileInputStream schemaIn = new FileInputStream(avsc); Schema original = new Schema.Parser().parse(schemaIn); schemaIn.close(); Schema evolved = getEvolvedSchema(original); FileOutputStream schemaOut = new FileOutputStream(evolvedAvsc); schemaOut.write(evolved.toString(true).getBytes()); schemaOut.close(); List<String> createArgs = Lists.newArrayList("create", dest, "-s", evolvedAvsc, "-r", repoUri, "-d", "target/data"); createArgs.addAll(getExtraCreateArgs()); TestUtil.run(LoggerFactory.getLogger(this.getClass()), "delete", dest, "-r", repoUri, "-d", "target/data"); TestUtil.run(LoggerFactory.getLogger(this.getClass()), createArgs.toArray(new String[createArgs.size()])); this.console = mock(Logger.class); this.command = new CopyCommand(console); command.setConf(new Configuration()); }
40. TypefaceFile#copyFile()
Project: jpexs-decompiler
File: TypefaceFile.java
File: TypefaceFile.java
private void copyFile(File a_in, File a_out) throws Exception { FileInputStream in = new FileInputStream(a_in); FileOutputStream out = new FileOutputStream(a_out); byte[] buffer = new byte[1024]; int i = 0; while ((i = in.read(buffer)) != -1) { out.write(buffer, 0, i); } // while in.close(); out.close(); }
41. JsonParserTest#testCitmCatalog()
Project: jodd
File: JsonParserTest.java
File: JsonParserTest.java
@Test public void testCitmCatalog() throws Exception { FileInputStream fis = new FileInputStream(new File(dataRoot, "citm_catalog.json.gz")); ByteArrayOutputStream out = new ByteArrayOutputStream(); StreamUtil.copy(new GZIPInputStream(fis), out); String json = out.toString("UTF-8"); fis.close(); JsonParser jsonParser = new JsonParser(); Map<String, Object> map; try { jsonParser.parse(json); map = jsonParser.parse(json); } catch (Exception ex) { fail(ex.toString()); throw ex; } assertNotNull(map); }
42. CatalogTest#loadJSON()
Project: jodd
File: CatalogTest.java
File: CatalogTest.java
private String loadJSON(String name) throws IOException { FileInputStream fis = new FileInputStream(new File(dataRoot, name + ".json.gz")); ByteArrayOutputStream out = new ByteArrayOutputStream(); StreamUtil.copy(new GZIPInputStream(fis), out); String json = out.toString("UTF-8"); fis.close(); return json; }
43. TestReadData#read_stream()
Project: jena
File: TestReadData.java
File: TestReadData.java
private static void read_stream(String filename, Lang lang) throws IOException { filename = filename(filename); // Read with a base @SuppressWarnings("deprecation") Dataset ds0 = DatasetFactory.createMem(); try (FileInputStream in0 = new FileInputStream(filename)) { RDFDataMgr.read(ds0, in0, "http://example/base2", lang); } // Read again, but without base @SuppressWarnings("deprecation") Dataset ds1 = DatasetFactory.createMem(); try (FileInputStream in1 = new FileInputStream(filename)) { RDFDataMgr.read(ds1, in1, null, lang); } }
44. TestLibrary#copyFile()
Project: jdk7u-jdk
File: TestLibrary.java
File: TestLibrary.java
public static void copyFile(File srcFile, File dstFile) throws IOException { FileInputStream src = new FileInputStream(srcFile); FileOutputStream dst = new FileOutputStream(dstFile); byte[] buf = new byte[32768]; while (true) { int count = src.read(buf); if (count < 0) { break; } dst.write(buf, 0, count); } dst.close(); src.close(); }
45. ICC_Profile#getInstance()
Project: jdk7u-jdk
File: ICC_Profile.java
File: ICC_Profile.java
/** * Constructs an ICC_Profile corresponding to the data in a file. * fileName may be an absolute or a relative file specification. * Relative file names are looked for in several places: first, relative * to any directories specified by the java.iccprofile.path property; * second, relative to any directories specified by the java.class.path * property; finally, in a directory used to store profiles always * available, such as the profile for sRGB. Built-in profiles use .pf as * the file name extension for profiles, e.g. sRGB.pf. * This method throws an IOException if the specified file cannot be * opened or if an I/O error occurs while reading the file. It throws * an IllegalArgumentException if the file does not contain valid ICC * Profile data. * @param fileName The file that contains the data for the profile. * * @return an <code>ICC_Profile</code> object corresponding to * the data in the specified file. * @exception IOException If the specified file cannot be opened or * an I/O error occurs while reading the file. * * @exception IllegalArgumentException If the file does not * contain valid ICC Profile data. * * @exception SecurityException If a security manager is installed * and it does not permit read access to the given file. */ public static ICC_Profile getInstance(String fileName) throws IOException { ICC_Profile thisProfile; FileInputStream fis = null; File f = getProfileFile(fileName); if (f != null) { fis = new FileInputStream(f); } if (fis == null) { throw new IOException("Cannot open file " + fileName); } thisProfile = getInstance(fis); fis.close(); return thisProfile; }
46. AuFileReader#getAudioInputStream()
Project: jdk7u-jdk
File: AuFileReader.java
File: AuFileReader.java
/** * Obtains an audio stream from the File provided. The File must * point to valid audio file data. * @param file the File for which the <code>AudioInputStream</code> should be * constructed * @return an <code>AudioInputStream</code> object based on the audio file data pointed * to by the File * @throws UnsupportedAudioFileException if the File does not point to valid audio * file data recognized by the system * @throws IOException if an I/O exception occurs */ public AudioInputStream getAudioInputStream(File file) throws UnsupportedAudioFileException, IOException { FileInputStream fis = null; BufferedInputStream bis = null; AudioFileFormat fileFormat = null; // throws IOException fis = new FileInputStream(file); AudioInputStream result = null; // part of fix for 4325421 try { bis = new BufferedInputStream(fis, bisBufferSize); result = getAudioInputStream((InputStream) bis); } finally { if (result == null) { fis.close(); } } return result; }
47. AuFileReader#getAudioFileFormat()
Project: jdk7u-jdk
File: AuFileReader.java
File: AuFileReader.java
/** * Obtains the audio file format of the File provided. The File must * point to valid audio file data. * @param file the File from which file format information should be * extracted * @return an <code>AudioFileFormat</code> object describing the audio file format * @throws UnsupportedAudioFileException if the File does not point to valid audio * file data recognized by the system * @throws IOException if an I/O exception occurs */ public AudioFileFormat getAudioFileFormat(File file) throws UnsupportedAudioFileException, IOException { FileInputStream fis = null; BufferedInputStream bis = null; AudioFileFormat fileFormat = null; AudioFormat format = null; // throws IOException fis = new FileInputStream(file); // part of fix for 4325421 try { bis = new BufferedInputStream(fis, bisBufferSize); // throws UnsupportedAudioFileException fileFormat = getAudioFileFormat(bis); } finally { fis.close(); } return fileFormat; }
48. FileUtil#readBytesFromFile()
Project: h-store
File: FileUtil.java
File: FileUtil.java
public static byte[] readBytesFromFile(String path) throws IOException { File file = new File(path); FileInputStream in = new FileInputStream(file); // Create the byte array to hold the data long length = file.length(); byte[] bytes = new byte[(int) length]; LOG.debug("Reading in the contents of '" + file.getAbsolutePath() + "'"); // Read in the bytes int offset = 0; int numRead = 0; while ((offset < bytes.length) && ((numRead = in.read(bytes, offset, bytes.length - offset)) >= 0)) { offset += numRead; } // WHILE if (offset < bytes.length) { throw new IOException("Failed to read the entire contents of '" + file.getName() + "'"); } in.close(); return (bytes); }
49. Utilities#readFile()
Project: grobid
File: Utilities.java
File: Utilities.java
/** * Read a file and return the content. * * @param pPathToFile * path to file to read. * @return String contained in the document. * @throws IOException */ public static String readFile(String pPathToFile) throws IOException { StringBuffer out = new StringBuffer(); FileInputStream inputStrem = new FileInputStream(new File(pPathToFile)); ByteArrayOutputStream outStream = new ByteArrayOutputStream(); byte buf[] = new byte[1024]; int len; while ((len = inputStrem.read(buf)) > 0) { outStream.write(buf, 0, len); out.append(outStream.toString()); } inputStrem.close(); outStream.close(); return out.toString(); }
50. Weblogic81Utils#initialize()
Project: geronimo
File: Weblogic81Utils.java
File: Weblogic81Utils.java
private void initialize(ClassLoader loader, File state) throws IOException, IllegalAccessException, NoSuchMethodException, InvocationTargetException, ClassNotFoundException, InstantiationException { byte[] salt = null, key = null; FileInputStream in = new FileInputStream(state); salt = readBytes(in); int i = in.read(); if (i != -1) { if (i != 1) throw new IllegalStateException(); key = readBytes(in); } in.close(); decrypter = getEncryptionService(loader, salt, key); decoder = loader.loadClass("weblogic.utils.encoders.BASE64Decoder").newInstance(); decode = decoder.getClass().getMethod("decodeBuffer", new Class[] { String.class }); decrypt = decrypter.getClass().getMethod("decryptString", new Class[] { byte[].class }); }
51. FeatureConfigParserTest#testFeatureConfigParser()
Project: geowave
File: FeatureConfigParserTest.java
File: FeatureConfigParserTest.java
@Test public void testFeatureConfigParser() throws IOException { FeatureConfigParser fcp = new FeatureConfigParser(); FeatureDefinitionSet fds = null; FileInputStream fis = new FileInputStream(new File(TEST_DATA_CONFIG)); // fds = fcp.parseConfig(fis); fis.close(); }
52. FileUtils#getStringFromFile()
Project: Gadgetbridge
File: FileUtils.java
File: FileUtils.java
public static String getStringFromFile(File file) throws IOException { FileInputStream fin = new FileInputStream(file); BufferedReader reader = new BufferedReader(new InputStreamReader(fin)); StringBuilder sb = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { sb.append(line).append("\n"); } reader.close(); fin.close(); return sb.toString(); }
53. MinaClientAuthTest#createFTPClient()
Project: ftpserver
File: MinaClientAuthTest.java
File: MinaClientAuthTest.java
protected FTPSClient createFTPClient() throws Exception { FTPSClient client = new FTPSClient(useImplicit()); client.setNeedClientAuth(true); KeyStore ks = KeyStore.getInstance("JKS"); FileInputStream fis = new FileInputStream(FTPCLIENT_KEYSTORE); ks.load(fis, KEYSTORE_PASSWORD.toCharArray()); fis.close(); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(ks, KEYSTORE_PASSWORD.toCharArray()); client.setKeyManager(kmf.getKeyManagers()[0]); return client; }
54. MP3Filter#main()
Project: fred
File: MP3Filter.java
File: MP3Filter.java
public static void main(String[] args) throws DataFilterException, IOException { File f = new File(args[0]); FileInputStream fis = new FileInputStream(f); File out = new File(args[0] + ".filtered.mp3"); FileOutputStream fos = new FileOutputStream(out); MP3Filter filter = new MP3Filter(); // // Skip some bytes for testing resyncing. // byte[] buf = new byte[4096]; // fis.read(buf); // fis.read(buf); // fis.read(buf); // fis.read(buf); filter.readFilter(fis, fos, null, null, null); fis.close(); fos.close(); }
55. Constants#copyFile()
Project: ForgeGradle
File: Constants.java
File: Constants.java
/** * This method uses the channels API which uses direct filesystem copies instead of loading it into * ram and then outputting it. * @param in file to copy * @param out created with directories if needed * @param size If you have it earlier * @throws IOException In case anything goes wrong with the file IO */ public static void copyFile(File in, File out, long size) throws IOException { // make dirs just in case out.getParentFile().mkdirs(); FileInputStream fis = new FileInputStream(in); FileOutputStream fout = new FileOutputStream(out); FileChannel source = fis.getChannel(); FileChannel dest = fout.getChannel(); source.transferTo(0, size, dest); fis.close(); fout.close(); }
56. Constants#copyFile()
Project: ForgeGradle
File: Constants.java
File: Constants.java
/** * This method uses the channels API which uses direct filesystem copies instead of loading it into * ram and then outputting it. * @param in file to copy * @param out created with directories if needed * @throws IOException In case anything goes wrong with the file IO */ public static void copyFile(File in, File out) throws IOException { // make dirs just in case out.getParentFile().mkdirs(); FileInputStream fis = new FileInputStream(in); FileOutputStream fout = new FileOutputStream(out); FileChannel source = fis.getChannel(); FileChannel dest = fout.getChannel(); long size = source.size(); source.transferTo(0, size, dest); fis.close(); fout.close(); }
57. ProcessCorpus#processLabeledData()
Project: fnlp
File: ProcessCorpus.java
File: ProcessCorpus.java
public static void processLabeledData(String input, String output) throws Exception { FileInputStream is = new FileInputStream(input); //skip BOM is.skip(3); BufferedReader r = new BufferedReader(new InputStreamReader(is, "utf8")); OutputStreamWriter w = new OutputStreamWriter(new FileOutputStream(output), "utf8"); while (true) { String sent = r.readLine(); if (null == sent) break; String s = Tags.genSegSequence(sent, delimer, 4); w.write(s); } r.close(); w.close(); }
58. DupDetector#loadData()
Project: fnlp
File: DupDetector.java
File: DupDetector.java
public void loadData(String fileList) throws IOException { int id = 0; FileInputStream fi = new FileInputStream(fileList); Scanner scanner = new Scanner(fi, "UTF8"); docs = new ArrayList<Documents>(); while (scanner.hasNext()) { String ss = scanner.nextLine().trim(); if (ss.length() < minLen) continue; Documents d = new Documents(ss); docs.add(d); } scanner.close(); fi.close(); }
59. TestTailSourceCursor#testFileDescriptor()
Project: flume
File: TestTailSourceCursor.java
File: TestTailSourceCursor.java
// ///////////////////////////////////////////////////////////////////////// /** * This an experiment playing with FileDescriptors. * * This doesn't test flume per se but is a jvm operating system consistency * check. */ @Test public void testFileDescriptor() throws IOException { File f = FileUtil.createTempFile("fdes", ".tmp"); f.deleteOnExit(); File f2 = FileUtil.createTempFile("fdes", ".tmp"); f2.delete(); f2.deleteOnExit(); FileInputStream fis = new FileInputStream(f); FileDescriptor fd = fis.getFD(); f.renameTo(f2); FileDescriptor fd2 = fis.getFD(); assertEquals(fd, fd2); new File(f.getAbsolutePath()).createNewFile(); FileInputStream fis2 = new FileInputStream(f); FileDescriptor fd3 = fis2.getFD(); assertTrue(fd3 != fd); }
60. SuiteResponderTest#normalSuiteRunProducesIndivualTestHistoryFile()
Project: fitnesse
File: SuiteResponderTest.java
File: SuiteResponderTest.java
@Test public void normalSuiteRunProducesIndivualTestHistoryFile() throws Exception { TestSummary counts = new TestSummary(1, 0, 0, 0); String resultsFileName = String.format("%s/SuitePage.SlimTest/20081205011900_%d_%d_%d_%d.xml", context.getTestHistoryDirectory(), counts.getRight(), counts.getWrong(), counts.getIgnores(), counts.getExceptions()); File xmlResultsFile = new File(resultsFileName); if (xmlResultsFile.exists()) xmlResultsFile.delete(); addTestToSuite("SlimTest", simpleSlimDecisionTable); runSuite(); assertTrue(resultsFileName, xmlResultsFile.exists()); FileInputStream xmlResultsStream = new FileInputStream(xmlResultsFile); XmlUtil.newDocument(xmlResultsStream); xmlResultsStream.close(); xmlResultsFile.delete(); }
61. SuiteResponderTest#normalSuiteRunWithThreePassingTestsProducesSuiteResultFile()
Project: fitnesse
File: SuiteResponderTest.java
File: SuiteResponderTest.java
@Test public void normalSuiteRunWithThreePassingTestsProducesSuiteResultFile() throws Exception { File xmlResultsFile = expectedXmlResultsFile(); if (xmlResultsFile.exists()) xmlResultsFile.delete(); addTestToSuite("SlimTestOne", simpleSlimDecisionTable); addTestToSuite("SlimTestTwo", simpleSlimDecisionTable); runSuite(); FileInputStream xmlResultsStream = new FileInputStream(xmlResultsFile); XmlUtil.newDocument(xmlResultsStream); xmlResultsStream.close(); xmlResultsFile.delete(); }
62. EDAMDemo#readFileAsData()
Project: evernote-sdk-java
File: EDAMDemo.java
File: EDAMDemo.java
/** * Helper method to read the contents of a file on disk and create a new Data * object. */ private static Data readFileAsData(String fileName) throws Exception { String filePath = new File(EDAMDemo.class.getResource(EDAMDemo.class.getCanonicalName() + ".class").getPath()).getParent() + File.separator + fileName; // Read the full binary contents of the file FileInputStream in = new FileInputStream(filePath); ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); byte[] block = new byte[10240]; int len; while ((len = in.read(block)) >= 0) { byteOut.write(block, 0, len); } in.close(); byte[] body = byteOut.toByteArray(); // Create a new Data object to contain the file contents Data data = new Data(); data.setSize(body.length); data.setBodyHash(MessageDigest.getInstance("MD5").digest(body)); data.setBody(body); return data; }
63. TestJsonReader#gzipIt()
Project: drill
File: TestJsonReader.java
File: TestJsonReader.java
public static void gzipIt(File sourceFile) throws IOException { // modified from: http://www.mkyong.com/java/how-to-compress-a-file-in-gzip-format/ byte[] buffer = new byte[1024]; GZIPOutputStream gzos = new GZIPOutputStream(new FileOutputStream(sourceFile.getPath() + ".gz")); FileInputStream in = new FileInputStream(sourceFile); int len; while ((len = in.read(buffer)) > 0) { gzos.write(buffer, 0, len); } in.close(); gzos.finish(); gzos.close(); }
64. SslBrokerServiceTest#loadClientCredential()
Project: activemq-artemis
File: SslBrokerServiceTest.java
File: SslBrokerServiceTest.java
private static byte[] loadClientCredential(String fileName) throws IOException { if (fileName == null) { return null; } FileInputStream in = new FileInputStream(fileName); ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buf = new byte[512]; int i = in.read(buf); while (i > 0) { out.write(buf, 0, i); i = in.read(buf); } in.close(); return out.toByteArray(); }
65. ActiveMQSslConnectionFactoryTest#loadClientCredential()
Project: activemq-artemis
File: ActiveMQSslConnectionFactoryTest.java
File: ActiveMQSslConnectionFactoryTest.java
private static byte[] loadClientCredential(String fileName) throws IOException { if (fileName == null) { return null; } FileInputStream in = new FileInputStream(fileName); ByteArrayOutputStream out = new ByteArrayOutputStream(); byte[] buf = new byte[512]; int i = in.read(buf); while (i > 0) { out.write(buf, 0, i); i = in.read(buf); } in.close(); return out.toByteArray(); }
66. FileCopier#copyFile()
Project: camelinaction
File: FileCopier.java
File: FileCopier.java
private static void copyFile(File source, File dest) throws IOException { OutputStream out = new FileOutputStream(dest); byte[] buffer = new byte[(int) source.length()]; FileInputStream in = new FileInputStream(source); in.read(buffer); try { out.write(buffer); } finally { out.close(); in.close(); } }
67. SiteMapGeneratorTest#convertFileToString()
Project: broadleaf_modify
File: SiteMapGeneratorTest.java
File: SiteMapGeneratorTest.java
protected String convertFileToString(File file) throws IOException { FileInputStream fin = new FileInputStream(file); BufferedReader br = new BufferedReader(new InputStreamReader(fin)); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { if (line.contains("</lastmod>")) { continue; } line = line.replaceAll("\\s+", ""); sb.append(line); } br.close(); fin.close(); return sb.toString(); }
68. SiteMapGeneratorTest#convertFileToString()
Project: BroadleafCommerce
File: SiteMapGeneratorTest.java
File: SiteMapGeneratorTest.java
protected String convertFileToString(File file) throws IOException { FileInputStream fin = new FileInputStream(file); BufferedReader br = new BufferedReader(new InputStreamReader(fin)); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { if (line.contains("</lastmod>")) { continue; } line = line.replaceAll("\\s+", ""); sb.append(line); } br.close(); fin.close(); return sb.toString(); }
69. ChunkParserTest#test()
Project: book
File: ChunkParserTest.java
File: ChunkParserTest.java
@Test public void test() throws IOException { File modelDir = getModelDir(); //<start id="openChunkParse"/> FileInputStream chunkerStream = new FileInputStream(new File(modelDir, "en-chunker.bin")); ChunkerModel chunkerModel = new ChunkerModel(chunkerStream); ChunkerME chunker = new ChunkerME(chunkerModel); FileInputStream posStream = new FileInputStream(new File(modelDir, "en-pos-maxent.bin")); POSModel posModel = new POSModel(posStream); POSTaggerME tagger = new POSTaggerME(posModel); Parser parser = new ChunkParser(chunker, tagger); Parse[] results = ParserTool.parseLine("The Minnesota Twins , " + "the 1991 World Series Champions , are currently in third place .", parser, 1); Parse p = results[0]; Parse[] chunks = p.getChildren(); assertTrue(chunks.length == 9); assertTrue(chunks[0].getType().equals("NP")); assertTrue(chunks[0].getHead().toString().equals("Twins")); //<end id="openChunkParse"/> }
70. AnswerTypeTest#test()
Project: book
File: AnswerTypeTest.java
File: AnswerTypeTest.java
@Test public void test() throws IOException { File modelDir = getModelDir(); AnswerTypeContextGenerator atcg = new AnswerTypeContextGenerator(new File(getWordNetDictionary().getAbsolutePath())); //<start id="answerType"/> FileInputStream chunkerStream = new FileInputStream(new File(modelDir, "en-chunker.bin")); ChunkerModel chunkerModel = new ChunkerModel(chunkerStream); ChunkerME chunker = new ChunkerME(chunkerModel); FileInputStream posStream = new FileInputStream(new File(modelDir, "en-pos-maxent.bin")); POSModel posModel = new POSModel(posStream); POSTaggerME tagger = new POSTaggerME(posModel); Parser parser = new ChunkParser(chunker, tagger); Parse[] results = ParserTool.parseLine("Who is the president of egypt ?", parser, 1); String[] context = atcg.getContext(results[0]); List<String> features = Arrays.asList(context); assertTrue(features.contains("qw=who")); assertTrue(features.contains("hw=president")); //entity assertTrue(features.contains("s=1740")); //person assertTrue(features.contains("s=7846")); //<end id="answerType"/> }
71. CMSProcessableFile#write()
Project: bc-java
File: CMSProcessableFile.java
File: CMSProcessableFile.java
public void write(OutputStream zOut) throws IOException, CMSException { FileInputStream fIn = new FileInputStream(file); int len; while ((len = fIn.read(buf, 0, buf.length)) > 0) { zOut.write(buf, 0, len); } fIn.close(); }
72. CMSProcessableFile#write()
Project: bc-java
File: CMSProcessableFile.java
File: CMSProcessableFile.java
public void write(OutputStream zOut) throws IOException, CMSException { FileInputStream fIn = new FileInputStream(file); int len; while ((len = fIn.read(buf, 0, buf.length)) > 0) { zOut.write(buf, 0, len); } fIn.close(); }
73. PGPUtil#pipeFileContents()
Project: bc-java
File: PGPUtil.java
File: PGPUtil.java
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) { pOut.write(buf, 0, len); } pOut.close(); in.close(); }
74. PropertyListParser#parse()
Project: bazel
File: PropertyListParser.java
File: PropertyListParser.java
/** * Parses a property list from a file. * * @param f The property list file. * @return The root object in the property list. This is usually a NSDictionary but can also be a NSArray. * @throws javax.xml.parsers.ParserConfigurationException If a document builder for parsing a XML property list * could not be created. This should not occur. * @throws java.io.IOException If any IO error occurs while reading the file. * @throws org.xml.sax.SAXException If any parse error occurs. * @throws com.dd.plist.PropertyListFormatException If the given property list has an invalid format. * @throws java.text.ParseException If a date string could not be parsed. */ public static NSObject parse(File f) throws IOException, PropertyListFormatException, ParseException, ParserConfigurationException, SAXException { FileInputStream fis = new FileInputStream(f); int type = determineType(fis); fis.close(); switch(type) { case TYPE_BINARY: return BinaryPropertyListParser.parse(f); case TYPE_XML: return XMLPropertyListParser.parse(f); case TYPE_ASCII: return ASCIIPropertyListParser.parse(f); default: throw new PropertyListFormatException("The given file is not a property list of a supported format."); } }
75. Subscription#configurationFromProperties()
Project: azure-shortcuts-for-java
File: Subscription.java
File: Subscription.java
/** * @param The file containing the credentials as a Java properties file * @param subscriptionId The desired subscription, if any * @return The Configuration object * @throws IOException * @throws InterruptedException * @throws ExecutionException * @throws URISyntaxException * @throws ServiceUnavailableException */ private static Configuration configurationFromProperties(File authFile, String subscriptionId) throws IOException, ServiceUnavailableException, URISyntaxException, ExecutionException, InterruptedException { FileInputStream authFileStream = new FileInputStream(authFile); Properties authSettings = new Properties(); authSettings.load(authFileStream); authFileStream.close(); if (subscriptionId == null) { // Read subscription from file if not provided subscriptionId = authSettings.getProperty(AuthSettings.SUBSCRIPTION_ID.toString()); } String tenantId = authSettings.getProperty(AuthSettings.TENANT_ID.toString()); String clientId = authSettings.getProperty(AuthSettings.CLIENT_ID.toString()); String clientKey = authSettings.getProperty(AuthSettings.CLIENT_KEY.toString()); String mgmtUri = authSettings.getProperty(AuthSettings.MANAGEMENT_URI.toString()); String authUrl = authSettings.getProperty(AuthSettings.AUTH_URL.toString()); String baseUrl = authSettings.getProperty(AuthSettings.BASE_URL.toString()); return createConfiguration(subscriptionId, tenantId, clientId, clientKey, mgmtUri, baseUrl, authUrl); }
76. Utils#replaceText()
Project: ATLauncher
File: Utils.java
File: Utils.java
/** * Replace text. * * @param originalFile the original file * @param destinationFile the destination file * @param replaceThis the replace this * @param withThis the with this * @throws IOException Signals that an I/O exception has occurred. */ public static void replaceText(File originalFile, File destinationFile, String replaceThis, String withThis) throws IOException { FileInputStream fs = new FileInputStream(originalFile); BufferedReader br = new BufferedReader(new InputStreamReader(fs)); FileWriter writer1 = new FileWriter(destinationFile); String line = br.readLine(); while (line != null) { if (line.contains(replaceThis)) { line = line.replace(replaceThis, withThis); } writer1.write(line); writer1.write(System.getProperty("line.separator")); line = br.readLine(); } writer1.flush(); writer1.close(); br.close(); fs.close(); }
77. ModellerTest#setup()
Project: aries
File: ModellerTest.java
File: ModellerTest.java
@BeforeClass public static void setup() throws Exception { URL pathToTestBundle = ModellerTest.class.getClassLoader().getResource("test.bundle"); File testBundleDir = new File(pathToTestBundle.toURI()); File outputArchive = new File(testBundleDir.getParentFile(), "test.bundle.jar"); FileInputStream fis = new FileInputStream(new File(testBundleDir, "META-INF/MANIFEST.MF")); Manifest manifest = new Manifest(fis); fis.close(); IOUtils.jarUp(testBundleDir, outputArchive, manifest); }
78. ModellerTest#setup()
Project: apache-aries
File: ModellerTest.java
File: ModellerTest.java
@BeforeClass public static void setup() throws Exception { URL pathToTestBundle = ModellerTest.class.getClassLoader().getResource("test.bundle"); File testBundleDir = new File(pathToTestBundle.toURI()); File outputArchive = new File(testBundleDir.getParentFile(), "test.bundle.jar"); FileInputStream fis = new FileInputStream(new File(testBundleDir, "META-INF/MANIFEST.MF")); Manifest manifest = new Manifest(fis); fis.close(); IOUtils.jarUp(testBundleDir, outputArchive, manifest); }
79. SWFParser#main()
Project: anthelion
File: SWFParser.java
File: SWFParser.java
/** * Arguments are: 0. Name of input SWF file. */ public static void main(String[] args) throws IOException { FileInputStream in = new FileInputStream(args[0]); byte[] buf = new byte[in.available()]; in.read(buf); SWFParser parser = new SWFParser(); ParseResult parseResult = parser.getParse(new Content("file:" + args[0], "file:" + args[0], buf, "application/x-shockwave-flash", new Metadata(), NutchConfiguration.create())); Parse p = parseResult.get("file:" + args[0]); System.out.println("Parse Text:"); System.out.println(p.getText()); System.out.println("Parse Data:"); System.out.println(p.getData()); }
80. CQLService#getSSLContext()
Project: Doradus
File: CQLService.java
File: CQLService.java
// getSSLOptions // Build an SSLContext from the given truststore and keystore parameters. private SSLContext getSSLContext(String truststorePath, String truststorePassword, String keystorePath, String keystorePassword) throws Exception { FileInputStream tsf = new FileInputStream(truststorePath); KeyStore ts = KeyStore.getInstance("JKS"); ts.load(tsf, truststorePassword.toCharArray()); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(ts); FileInputStream ksf = new FileInputStream(keystorePath); KeyStore ks = KeyStore.getInstance("JKS"); ks.load(ksf, keystorePassword.toCharArray()); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(ks, keystorePassword.toCharArray()); SSLContext ctx = SSLContext.getInstance("SSL"); ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), new SecureRandom()); return ctx; }
81. DB_Jar#doCopy()
Project: derby
File: DB_Jar.java
File: DB_Jar.java
private static void doCopy(String oldJarFileName, String newJarFileName) throws IOException { FileInputStream oldJarFile = new FileInputStream(oldJarFileName); FileOutputStream newJarFile = new FileOutputStream(newJarFileName); while (true) { if (oldJarFile.available() == 0) break; byte[] bAr = new byte[oldJarFile.available()]; oldJarFile.read(bAr); newJarFile.write(bAr); } oldJarFile.close(); newJarFile.close(); }
82. ShapefileHandlerTest#addToZipFile()
Project: dataverse
File: ShapefileHandlerTest.java
File: ShapefileHandlerTest.java
private boolean addToZipFile(String fileName, File fileToZip, ZipOutputStream zip_output_stream) throws FileNotFoundException, IOException { //File file = new File(fullFilepath); FileInputStream file_input_stream = new FileInputStream(fileToZip); ZipEntry zipEntry = new ZipEntry(fileName); zip_output_stream.putNextEntry(zipEntry); byte[] bytes = new byte[1024]; int length; while ((length = file_input_stream.read(bytes)) >= 0) { zip_output_stream.write(bytes, 0, length); } zip_output_stream.closeEntry(); file_input_stream.close(); return true; }
83. ZipMaker#addToZipFile()
Project: dataverse
File: ZipMaker.java
File: ZipMaker.java
public static void addToZipFile(String fileName, String fullFilepath, ZipOutputStream zip_output_stream) throws FileNotFoundException, IOException { if (DEBUG) { System.out.println("Writing '" + fileName + "' to zip file"); } File file = new File(fullFilepath); FileInputStream file_input_stream = new FileInputStream(file); ZipEntry zipEntry = new ZipEntry(fileName); zip_output_stream.putNextEntry(zipEntry); byte[] bytes = new byte[1024]; int length; while ((length = file_input_stream.read(bytes)) >= 0) { zip_output_stream.write(bytes, 0, length); } zip_output_stream.closeEntry(); file_input_stream.close(); }
84. DatabaseAttachmentTest#testGetContentURL()
Project: couchbase-lite-android
File: DatabaseAttachmentTest.java
File: DatabaseAttachmentTest.java
public void testGetContentURL() throws Exception { String attachmentName = "index.html"; String content = "This is a test attachment!"; Document doc = createDocWithAttachment(database, attachmentName, content); Attachment attachment = doc.getCurrentRevision().getAttachment(attachmentName); URL url = attachment.getContentURL(); assertNotNull(url); FileInputStream fis = new FileInputStream(new File(url.toURI())); byte[] buffer = new byte[1024]; int len = fis.read(buffer); assertTrue(len != -1); String content2 = new String(buffer, 0, len); assertEquals(content, content2); fis.close(); }
85. FileSystem#gzipFile()
Project: CoreNLP
File: FileSystem.java
File: FileSystem.java
/** * Similar to the unix gzip command, only it does not delete the file after compressing it. * * @param uncompressedFileName The file to gzip * @param compressedFileName The file name for the compressed file * @throws IOException */ public static void gzipFile(File uncompressedFileName, File compressedFileName) throws IOException { GZIPOutputStream out = new GZIPOutputStream(new FileOutputStream(compressedFileName)); FileInputStream in = new FileInputStream(uncompressedFileName); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } in.close(); out.finish(); out.close(); }
86. CameraLauncher#writeUncompressedImage()
Project: cordova-android-chromeview
File: CameraLauncher.java
File: CameraLauncher.java
/** * In the special case where the default width, height and quality are unchanged * we just write the file out to disk saving the expensive Bitmap.compress function. * * @param uri * @throws FileNotFoundException * @throws IOException */ private void writeUncompressedImage(Uri uri) throws FileNotFoundException, IOException { FileInputStream fis = new FileInputStream(FileHelper.stripFileProtocol(imageUri.toString())); OutputStream os = this.cordova.getActivity().getContentResolver().openOutputStream(uri); byte[] buffer = new byte[4096]; int len; while ((len = fis.read(buffer)) != -1) { os.write(buffer, 0, len); } os.flush(); os.close(); fis.close(); }
87. FileTransferReceiverTest#readBytesFromFile()
Project: community-edition
File: FileTransferReceiverTest.java
File: FileTransferReceiverTest.java
public static byte[] readBytesFromFile(File file) throws IOException { FileInputStream fileinputstream = new FileInputStream(file); long l = file.length(); if (l > Integer.MAX_VALUE) { throw new IOException("File too big for loading into a byte array!"); } byte byteArray[] = new byte[(int) l]; int i = 0; for (int j = 0; (i < byteArray.length) && (j = fileinputstream.read(byteArray, i, byteArray.length - i)) >= 0; i += j) ; if (i < byteArray.length) { throw new IOException("Could not completely read the file " + file.getName()); } fileinputstream.close(); return byteArray; }
88. TFTPTest#testUpload()
Project: commons-net
File: TFTPTest.java
File: TFTPTest.java
private void testUpload(int mode, File file) throws Exception { // Create our TFTP instance to handle the file transfer. TFTPClient tftp = new TFTPClient(); tftp.open(); tftp.setSoTimeout(2000); File in = new File(serverDirectory, filePrefix + "upload"); // cleanup old failed runs in.delete(); assertTrue("Couldn't clear output location", !in.exists()); FileInputStream fis = new FileInputStream(file); tftp.sendFile(in.getName(), mode, fis, "localhost", SERVER_PORT); fis.close(); // need to give the server a bit of time to receive our last packet, and // close out its file buffers, etc. Thread.sleep(100); assertTrue("file not created", in.exists()); assertTrue("files not identical on file " + file, filesIdentical(file, in)); in.delete(); }
89. ZipFileTest#testUnshrinking()
Project: commons-compress
File: ZipFileTest.java
File: ZipFileTest.java
@Test public void testUnshrinking() throws Exception { zf = new ZipFile(getFile("SHRUNK.ZIP")); ZipArchiveEntry test = zf.getEntry("TEST1.XML"); FileInputStream original = new FileInputStream(getFile("test1.xml")); try { assertArrayEquals(IOUtils.toByteArray(original), IOUtils.toByteArray(zf.getInputStream(test))); } finally { original.close(); } test = zf.getEntry("TEST2.XML"); original = new FileInputStream(getFile("test2.xml")); try { assertArrayEquals(IOUtils.toByteArray(original), IOUtils.toByteArray(zf.getInputStream(test))); } finally { original.close(); } }
90. TarArchiveOutputStreamTest#testPadsOutputToFullBlockLength()
Project: commons-compress
File: TarArchiveOutputStreamTest.java
File: TarArchiveOutputStreamTest.java
@Test public void testPadsOutputToFullBlockLength() throws Exception { final File f = File.createTempFile("commons-compress-padding", ".tar"); f.deleteOnExit(); final FileOutputStream fos = new FileOutputStream(f); final TarArchiveOutputStream tos = new TarArchiveOutputStream(fos); final File file1 = getFile("test1.xml"); final TarArchiveEntry sEntry = new TarArchiveEntry(file1, file1.getName()); tos.putArchiveEntry(sEntry); final FileInputStream in = new FileInputStream(file1); IOUtils.copy(in, tos); in.close(); tos.closeArchiveEntry(); tos.close(); // test1.xml is small enough to fit into the default block size assertEquals(TarConstants.DEFAULT_BLKSIZE, f.length()); }
91. FileUtil#copy()
Project: cloudhopper-commons
File: FileUtil.java
File: FileUtil.java
/** * Copy the source file to the target file while optionally permitting an * overwrite to occur in case the target file already exists. * @param sourceFile The source file to copy from * @param targetFile The target file to copy to * @return True if an overwrite occurred, otherwise false. * @throws FileAlreadyExistsException Thrown if the target file already * exists and an overwrite is not permitted. This exception is a * subclass of IOException, so catching an IOException is enough if you * don't care about this specific reason. * @throws IOException Thrown if an error during the copy */ public static boolean copy(File sourceFile, File targetFile, boolean overwrite) throws FileAlreadyExistsException, IOException { boolean overwriteOccurred = false; // check if the targetFile already exists if (targetFile.exists()) { // if overwrite is not allowed, throw an exception if (!overwrite) { throw new FileAlreadyExistsException("Target file " + targetFile + " already exists"); } else { // set the flag that it occurred overwriteOccurred = true; } } // proceed with copy FileInputStream fis = new FileInputStream(sourceFile); FileOutputStream fos = new FileOutputStream(targetFile); fis.getChannel().transferTo(0, sourceFile.length(), fos.getChannel()); fis.close(); fos.flush(); fos.close(); return overwriteOccurred; }
92. CMRTests#checkSha1()
Project: ceylon-compiler
File: CMRTests.java
File: CMRTests.java
private void checkSha1(File signatureFile) throws IOException { Assert.assertEquals(40, signatureFile.length()); FileInputStream reader = new FileInputStream(signatureFile); byte[] bytes = new byte[40]; Assert.assertEquals(40, reader.read(bytes)); reader.close(); char[] sha1 = new String(bytes, "ASCII").toCharArray(); for (int i = 0; i < sha1.length; i++) { char c = sha1[i]; Assert.assertTrue((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')); } }
93. CMRTests#checkSha1()
Project: ceylon
File: CMRTests.java
File: CMRTests.java
private void checkSha1(File signatureFile) throws IOException { Assert.assertEquals(40, signatureFile.length()); FileInputStream reader = new FileInputStream(signatureFile); byte[] bytes = new byte[40]; Assert.assertEquals(40, reader.read(bytes)); reader.close(); char[] sha1 = new String(bytes, "ASCII").toCharArray(); for (int i = 0; i < sha1.length; i++) { char c = sha1[i]; Assert.assertTrue((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F')); } }
94. AttachmentTest#testSaveInUserTemporaryArea()
Project: yobi
File: AttachmentTest.java
File: AttachmentTest.java
@Test public void testSaveInUserTemporaryArea() throws IOException, NoSuchAlgorithmException { // Given File file = createFileWithContents("foo.txt", "Hello".getBytes()); Long userId = 1L; // When Attachment attach = new Attachment(); attach.store(file, "bar.txt", User.find.byId(userId).asResource()); FileInputStream is = new FileInputStream(attach.getFile()); byte[] b = new byte[1024]; int length = is.read(b); is.close(); // Then assertThat(attach.name).isEqualTo("bar.txt"); assertThat(attach.mimeType).isEqualTo("text/plain; charset=UTF-8"); assertThat(new String(b, 0, length)).isEqualTo(new String("Hello")); }
95. XML#toXml()
Project: wink
File: XML.java
File: XML.java
/** * Method to take a JSON file and return a String of the XML format. * * @param xmlFile The JSON file to transform to XML. * @param verbose Boolean flag denoting whther or not to write the XML in verbose (formatted), or compact form (no whitespace) * @return A string of the XML representation of the JSON file * * @throws IOException Thrown if an IOError occurs. */ public static String toXml(File jsonFile, boolean verbose) throws IOException { if (logger.isLoggable(Level.FINER)) { logger.exiting(className, "toXml(InputStream, boolean)"); } FileInputStream fis = new FileInputStream(jsonFile); String result = null; result = toXml(fis, verbose); fis.close(); if (logger.isLoggable(Level.FINER)) { logger.exiting(className, "toXml(InputStream, boolean)"); } return result; }
96. XML#toJson()
Project: wink
File: XML.java
File: XML.java
/** * Method to take an XML file and return a String of the JSON format. * * @param xmlFile The XML file to transform to JSON. * @param verbose Boolean flag denoting whther or not to write the JSON in verbose (formatted), or compact form (no whitespace) * @return A string of the JSON representation of the XML file * * @throws SAXException Thrown if an error occurs during parse. * @throws IOException Thrown if an IOError occurs. */ public static String toJson(File xmlFile, boolean verbose) throws SAXException, IOException { if (logger.isLoggable(Level.FINER)) { logger.exiting(className, "toJson(InputStream, boolean)"); } FileInputStream fis = new FileInputStream(xmlFile); String result = null; result = toJson(fis, verbose); fis.close(); if (logger.isLoggable(Level.FINER)) { logger.exiting(className, "toJson(InputStream, boolean)"); } return result; }
97. HttpKnife#partFile()
Project: WeGit
File: HttpKnife.java
File: HttpKnife.java
/** * ???? * * @param dos * @param name * @param fileName * @param file * @throws IOException */ public HttpKnife partFile(String name, String fileName, File file) throws IOException { DataOutputStream dos = new DataOutputStream(openOutput()); dos.writeBytes("Content-Disposition: form-data; name=\"" + name + "\";filename=\"" + fileName + "\"" + CRLF); dos.writeBytes("Content-Type: " + URLConnection.guessContentTypeFromName(fileName)); dos.writeBytes(CRLF); dos.writeBytes(CRLF); System.out.println("guessContentTypeFromName " + URLConnection.guessContentTypeFromName(fileName)); FileInputStream inputStream = new FileInputStream(file); byte[] buffer = new byte[4096]; int bytesRead = -1; while ((bytesRead = inputStream.read(buffer)) != -1) { dos.write(buffer, 0, bytesRead); } dos.writeBytes(CRLF); inputStream.close(); return this; }
98. MessagesTestBase#readFile()
Project: vso-httpclient-java
File: MessagesTestBase.java
File: MessagesTestBase.java
/** * * @param f * @return * @throws IOException */ private String readFile(File f) throws IOException { //$NON-NLS-1$ assertTrue("File does not exist=" + f.getAbsolutePath(), f.exists()); FileInputStream in = new FileInputStream(f); byte[] bytes = new byte[(int) f.length()]; int bytesRead = in.read(bytes); //$NON-NLS-1$ assertEquals("Expected to read all bytes", f.length(), bytesRead); in.close(); return new String(bytes); }
99. TestLZF#_readData()
Project: voldemort
File: TestLZF.java
File: TestLZF.java
private static byte[] _readData(File in) throws IOException { int len = (int) in.length(); byte[] result = new byte[len]; int offset = 0; FileInputStream fis = new FileInputStream(in); while (len > 0) { int count = fis.read(result, offset, len); if (count < 0) break; len -= count; offset += count; } fis.close(); return result; }
100. RootbeerCompiler#readFile()
Project: rootbeer1
File: RootbeerCompiler.java
File: RootbeerCompiler.java
private byte[] readFile(File f) throws Exception { List<Byte> contents = new ArrayList<Byte>(); byte[] buffer = new byte[4096]; FileInputStream fin = new FileInputStream(f); while (true) { int len = fin.read(buffer); if (len == -1) break; for (int i = 0; i < len; ++i) { contents.add(buffer[i]); } } fin.close(); byte[] ret = new byte[contents.size()]; for (int i = 0; i < contents.size(); ++i) ret[i] = contents.get(i); return ret; }