java.io.FileInputStream

Here are the examples of the java api class java.io.FileInputStream taken from open source projects.

1. JcaPKIXIdentityBuilder#build()

Project: bc-java
Source File: JcaPKIXIdentityBuilder.java
View license
/**
     * 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
Source File: Cluster.java
View license
// 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. XMPacker#unpack()

Project: XM-File-Format
Source File: XMPacker.java
View license
/*
	 * 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();
}

4. XMLoader#loadImageXMI()

Project: XM-File-Format
Source File: XMLoader.java
View license
/*
	 * 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. XMLoader#loadImageXMM()

Project: XM-File-Format
Source File: XMLoader.java
View license
/*
	 * 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);
}

6. AvlTreePerfTest#testAVLTreeDeserializationPerf()

View license
@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. TestSiddhiStateSnapshotAndRestore#testSimpleSiddhiQuery()

View license
@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();
}

8. APPIOSApplication#getFormat()

Project: ios-driver
Source File: APPIOSApplication.java
View license
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;
    }
}

9. RandomAccessFileTest#test_write$BII()

Project: j2objc
Source File: RandomAccessFileTest.java
View license
/**
     * 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();
}

10. FileIOStreamT#main()

View license
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();
}

11. TestJenaReaderRIOT#jenaread_stream()

Project: jena
Source File: TestJenaReaderRIOT.java
View license
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);
}

12. FileAppenderTest#verifyFile()

View license
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();
}

13. ThumbnailatorTest#testCreateThumbnail_IOII_Bmp()

View license
/**
	 * Test for
	 * [email protected] 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. ActiveMQSslConnectionFactoryTest#loadClientCredential()

View license
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();
}

15. SslBrokerServiceTest#loadClientCredential()

View license
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();
}

16. SWFParser#main()

Project: anthelion
Source File: SWFParser.java
View license
/**
   * 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());
}

17. ModellerTest#setup()

Project: apache-aries
Source File: ModellerTest.java
View license
@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);
}

18. ModellerTest#setup()

Project: aries
Source File: ModellerTest.java
View license
@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);
}

19. Utils#replaceText()

Project: ATLauncher
Source File: Utils.java
View license
/**
     * 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();
}

20. Subscription#configurationFromProperties()

View license
/**
     * @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);
}

21. PropertyListParser#parse()

Project: bazel
Source File: PropertyListParser.java
View license
/**
     * 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.");
    }
}

22. PGPUtil#pipeFileContents()

Project: bc-java
Source File: PGPUtil.java
View license
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();
}

23. CMSProcessableFile#write()

Project: bc-java
Source File: CMSProcessableFile.java
View license
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();
}

24. CMSProcessableFile#write()

Project: bc-java
Source File: CMSProcessableFile.java
View license
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();
}

25. AnswerTypeTest#test()

Project: book
Source File: AnswerTypeTest.java
View license
@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"/>
}

26. ChunkParserTest#test()

Project: book
Source File: ChunkParserTest.java
View license
@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"/>
}

27. SiteMapGeneratorTest#convertFileToString()

View license
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();
}

28. SiteMapGeneratorTest#convertFileToString()

View license
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();
}

29. FileCopier#copyFile()

Project: camelinaction
Source File: FileCopier.java
View license
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();
    }
}

30. CMRTests#checkSha1()

Project: ceylon
Source File: CMRTests.java
View license
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'));
    }
}

31. CMRTests#checkSha1()

Project: ceylon-compiler
Source File: CMRTests.java
View license
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'));
    }
}

32. FileUtil#copy()

Project: cloudhopper-commons
Source File: FileUtil.java
View license
/**
     * 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;
}

33. TarArchiveOutputStreamTest#testPadsOutputToFullBlockLength()

View license
@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());
}

34. ZipFileTest#testUnshrinking()

Project: commons-compress
Source File: ZipFileTest.java
View license
@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();
    }
}

35. TFTPTest#testUpload()

Project: commons-net
Source File: TFTPTest.java
View license
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();
}

36. FileTransferReceiverTest#readBytesFromFile()

View license
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;
}

37. CameraLauncher#writeUncompressedImage()

View license
/**
     * 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();
}

38. FileSystem#gzipFile()

Project: CoreNLP
Source File: FileSystem.java
View license
/**
   * 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();
}

39. DatabaseAttachmentTest#testGetContentURL()

View license
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();
}

40. ZipMaker#addToZipFile()

Project: dataverse
Source File: ZipMaker.java
View license
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();
}

41. ShapefileHandlerTest#addToZipFile()

Project: dataverse
Source File: ShapefileHandlerTest.java
View license
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;
}

42. DB_Jar#doCopy()

Project: derby
Source File: DB_Jar.java
View license
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();
}

43. CQLService#getSSLContext()

Project: Doradus
Source File: CQLService.java
View license
// 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;
}

44. TestJsonReader#gzipIt()

Project: drill
Source File: TestJsonReader.java
View license
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();
}

45. EDAMDemo#readFileAsData()

Project: evernote-sdk-java
Source File: EDAMDemo.java
View license
/**
   * 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;
}

46. SuiteResponderTest#normalSuiteRunWithThreePassingTestsProducesSuiteResultFile()

Project: fitnesse
Source File: SuiteResponderTest.java
View license
@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();
}

47. SuiteResponderTest#normalSuiteRunProducesIndivualTestHistoryFile()

Project: fitnesse
Source File: SuiteResponderTest.java
View license
@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();
}

48. TestTailSourceCursor#testFileDescriptor()

Project: flume
Source File: TestTailSourceCursor.java
View license
// /////////////////////////////////////////////////////////////////////////
/**
   * 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);
}

49. DupDetector#loadData()

Project: fnlp
Source File: DupDetector.java
View license
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();
}

50. ProcessCorpus#processLabeledData()

Project: fnlp
Source File: ProcessCorpus.java
View license
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();
}

51. Constants#copyFile()

Project: ForgeGradle
Source File: Constants.java
View license
/**
     * 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();
}

52. Constants#copyFile()

Project: ForgeGradle
Source File: Constants.java
View license
/**
     * 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();
}

53. MP3Filter#main()

Project: fred
Source File: MP3Filter.java
View license
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();
}

54. MinaClientAuthTest#createFTPClient()

Project: ftpserver
Source File: MinaClientAuthTest.java
View license
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;
}

55. FileUtils#getStringFromFile()

Project: Gadgetbridge
Source File: FileUtils.java
View license
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();
}

56. FeatureConfigParserTest#testFeatureConfigParser()

View license
@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();
}

57. Weblogic81Utils#initialize()

Project: geronimo
Source File: Weblogic81Utils.java
View license
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 });
}

58. Utilities#readFile()

Project: grobid
Source File: Utilities.java
View license
/**
	 * 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();
}

59. FileUtil#readBytesFromFile()

Project: h-store
Source File: FileUtil.java
View license
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);
}

60. TestIO#testCustomTypesIO()

Project: hadoop-mapreduce
Source File: TestIO.java
View license
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();
}

61. OldFileChannelTest#test_forceZ()

Project: j2objc
Source File: OldFileChannelTest.java
View license
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();
}

62. AbstractApplication#loadConfig()

View license
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());
}

63. AnsiConsoleExample#main()

Project: jansi
Source File: AnsiConsoleExample.java
View license
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();
}

64. AnsiConsoleExample2#main()

Project: jansi
Source File: AnsiConsoleExample2.java
View license
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("=======================================================================");
}

65. CopyFileT#copyFile()

View license
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();
}

66. MKVDemuxerTest#setUp()

Project: jcodec
Source File: MKVDemuxerTest.java
View license
@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()));
}

67. AuFileReader#getAudioFileFormat()

Project: jdk7u-jdk
Source File: AuFileReader.java
View license
/**
     * 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;
}

68. AuFileReader#getAudioInputStream()

Project: jdk7u-jdk
Source File: AuFileReader.java
View license
/**
     * 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;
}

69. ICC_Profile#getInstance()

Project: jdk7u-jdk
Source File: ICC_Profile.java
View license
/**
     * 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;
}

70. TestLibrary#copyFile()

Project: jdk7u-jdk
Source File: TestLibrary.java
View license
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();
}

71. TestReadData#read_stream()

Project: jena
Source File: TestReadData.java
View license
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);
    }
}

72. CatalogTest#loadJSON()

Project: jodd
Source File: CatalogTest.java
View license
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;
}

73. JsonParserTest#testCitmCatalog()

Project: jodd
Source File: JsonParserTest.java
View license
@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);
}

74. TypefaceFile#copyFile()

Project: jpexs-decompiler
Source File: TypefaceFile.java
View license
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();
}

75. TestCopyCommandClusterSchemaEvolution#createDestination()

View license
@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());
}

76. InvertedIndexLocalTest#setUp()

Project: kylin
Source File: InvertedIndexLocalTest.java
View license
@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);
}

77. ReTokenizeFile#readFile()

Project: lenya
Source File: ReTokenizeFile.java
View license
/**
     * 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();
}

78. Grep#containsPattern()

Project: lenya
Source File: Grep.java
View license
/**
     * 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;
}

79. JarFileCopy#toCopy()

Project: LGame
Source File: JarFileCopy.java
View license
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++;
}

80. FileIO#copyFile()

Project: librec
Source File: FileIO.java
View license
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();
}

81. FileStoreClient#getFileContent()

Project: linkbinder
Source File: FileStoreClient.java
View license
/**
     * 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);
    }
}

82. ZipLibrary#zipFile()

Project: mcMMO
Source File: ZipLibrary.java
View license
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();
}

83. UnicodeWriterTest#test()

Project: metamodel
Source File: UnicodeWriterTest.java
View license
@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();
}

84. DataTypeTranslater#fileToByte()

View license
/**
	 * ???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;
}

85. Storage#openScore()

View license
/**
   * 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();
}

86. RssConfiguration#initialize()

Project: oodt
Source File: RssConfiguration.java
View license
/**
   * 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();
}

87. DatasetZipWriter#writeTo()

Project: oodt
Source File: DatasetZipWriter.java
View license
@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();
}

88. ProductZipWriter#writeTo()

Project: oodt
Source File: ProductZipWriter.java
View license
@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();
}

89. CmsFileUtil#copy()

Project: opencms-core
Source File: CmsFileUtil.java
View license
/**
     * 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();
}

90. CmsSetupTestSimapi#readFile()

View license
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();
}

91. TestLibrary#copyFile()

Project: openjdk
Source File: TestLibrary.java
View license
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();
}

92. SynonymMap#loadFromFile()

Project: opensearchserver
Source File: SynonymMap.java
View license
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();
}

93. ScreenshotTest#digest()

View license
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();
}

94. TestTempUtils#testCopyIntoTempFile()

Project: PalDB
Source File: TestTempUtils.java
View license
@Test
public void testCopyIntoTempFile() throws IOException {
    ByteArrayInputStream bis = new ByteArrayInputStream("foo".getBytes());
    File file = TempUtils.copyIntoTempFile("bar", bis);
    Assert.assertTrue(file.exists());
    Assert.assertTrue(file.isFile());
    Assert.assertTrue(file.getName().contains("bar"));
    Assert.assertEquals(bis.available(), 0);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    FileInputStream fis = new FileInputStream(file);
    byte[] buffer = new byte[8192];
    int length;
    while ((length = fis.read(buffer)) > 0) {
        bos.write(buffer, 0, length);
    }
    fis.close();
    bos.close();
    Assert.assertEquals(bos.toByteArray(), "foo".getBytes());
}

95. TestParamSubPreproc#testCmdlineParam()

Project: pig
Source File: TestParamSubPreproc.java
View license
/* Test case 1
     * Use a parameter within a pig script and provide value on the command line.
     */
@Test
public void testCmdlineParam() throws Exception {
    log.info("Starting test testCmdlineParam() ...");
    ParameterSubstitutionPreprocessor ps = new ParameterSubstitutionPreprocessor(50);
    pigIStream = new BufferedReader(new FileReader(basedir + "/input1.pig"));
    pigOStream = new FileWriter(basedir + "/output1.pig");
    String[] arg = { "date=20080228" };
    String[] argFiles = null;
    ps.genSubstitutedFile(pigIStream, pigOStream, arg, argFiles);
    FileInputStream pigResultStream = new FileInputStream(basedir + "/output1.pig");
    pigExResultStream = new FileInputStream(basedir + "/ExpectedResult.pig");
    compareResults(pigExResultStream, pigResultStream);
    log.info("Done");
}

96. TestParamSubPreproc#testFileParam()

Project: pig
Source File: TestParamSubPreproc.java
View license
/* Test case 2
     * Use a parameter within a pig script and provide value through a file.
     */
@Test
public void testFileParam() throws Exception {
    log.info("Starting test  testFileParam()");
    ParameterSubstitutionPreprocessor ps = new ParameterSubstitutionPreprocessor(50);
    pigIStream = new BufferedReader(new FileReader(basedir + "/input1.pig"));
    pigOStream = new FileWriter(basedir + "/output1.pig");
    String[] arg = null;
    String[] argFiles = { basedir + "/ConfFile1.txt" };
    ps.genSubstitutedFile(pigIStream, pigOStream, arg, argFiles);
    FileInputStream pigResultStream = new FileInputStream(basedir + "/output1.pig");
    pigExResultStream = new FileInputStream(basedir + "/ExpectedResult.pig");
    compareResults(pigExResultStream, pigResultStream);
    log.info("Done");
}

97. TestParamSubPreproc#testShellCommand()

Project: pig
Source File: TestParamSubPreproc.java
View license
/* Test case 3
     *  Use a parameter within a pig script and provide value through running a binary or script.
     */
@Test
public void testShellCommand() throws Exception {
    log.info("Starting test testShellCommand()");
    ParameterSubstitutionPreprocessor ps = new ParameterSubstitutionPreprocessor(50);
    pigIStream = WithConditionalReplacement(basedir + "/input4.pig", "sh test/org/apache/pig/test/data/generate_date.sh", "test/org/apache/pig/test/data/generate_date.bat", Shell.WINDOWS);
    pigOStream = new FileWriter(basedir + "/output1.pig");
    //{"date=`sh generate_date.sh`"};     //`date \\T`"};
    String[] arg = null;
    // {basedir+"/ConfFile1.txt"};
    String[] argFiles = null;
    ps.genSubstitutedFile(pigIStream, pigOStream, arg, argFiles);
    FileInputStream pigResultStream = new FileInputStream(basedir + "/output1.pig");
    pigExResultStream = new FileInputStream(basedir + "/ExpectedResultDefault.pig");
    compareResults(pigExResultStream, pigResultStream);
    log.info("Done");
}

98. TestParamSubPreproc#testSubstitutionWithinValue()

Project: pig
Source File: TestParamSubPreproc.java
View license
/* Test case 7
     *  Use a parameter in %declare that is defined in terms of other parameters
     */
@Test
public void testSubstitutionWithinValue() throws Exception {
    log.info("Starting test  testSubstitutionWithinValue()");
    ParameterSubstitutionPreprocessor ps = new ParameterSubstitutionPreprocessor(50);
    pigIStream = new BufferedReader(new FileReader(basedir + "/inputSubstitutionWithinValue.pig"));
    pigOStream = new FileWriter(basedir + "/output1.pig");
    String[] arg = null;
    String[] argFiles = { basedir + "/ConfFile1.txt" };
    ps.genSubstitutedFile(pigIStream, pigOStream, arg, argFiles);
    FileInputStream pigResultStream = new FileInputStream(basedir + "/output1.pig");
    pigExResultStream = new FileInputStream(basedir + "/ExpectedResult4.pig");
    compareResults(pigExResultStream, pigResultStream);
    log.info("Done");
}

99. TestParamSubPreproc#testSubstitutionWithinShellCommand()

Project: pig
Source File: TestParamSubPreproc.java
View license
/* Test case 8
     *  Use a parameter within a pig script, provide value for it through running a binary or script.
     *  The script itself takes an argument that is a parameter and should be resolved
     */
@Test
public void testSubstitutionWithinShellCommand() throws Exception {
    log.info("Starting test testSubstitutionWithinShellCommand()");
    ParameterSubstitutionPreprocessor ps = new ParameterSubstitutionPreprocessor(50);
    pigIStream = WithConditionalReplacement(basedir + "/inputSubstitutionWithinShellCommand.pig", "sh test/org/apache/pig/test/data/generate_date.sh", "test/org/apache/pig/test/data/generate_date.bat", Shell.WINDOWS);
    pigOStream = new FileWriter(basedir + "/output1.pig");
    String[] arg = null;
    String[] argFiles = null;
    ps.genSubstitutedFile(pigIStream, pigOStream, arg, argFiles);
    FileInputStream pigResultStream = new FileInputStream(basedir + "/output1.pig");
    pigExResultStream = new FileInputStream(basedir + "/ExpectedResult4.pig");
    compareResults(pigExResultStream, pigResultStream);
    log.info("Done");
}

100. TestParamSubPreproc#testCmdlineParamPriortoDeclare()

Project: pig
Source File: TestParamSubPreproc.java
View license
/* Test case 9
     *  Use parameters passed on the command line/file that are not resolved prior to the declare statement.
     */
@Test
public void testCmdlineParamPriortoDeclare() throws Exception {
    log.info("Starting test testCmdlineParamPriortoDeclare()");
    ParameterSubstitutionPreprocessor ps = new ParameterSubstitutionPreprocessor(50);
    pigIStream = new BufferedReader(new FileReader(basedir + "/input2.pig"));
    pigOStream = new FileWriter(basedir + "/output1.pig");
    String[] arg = { "param='20080228'" };
    String[] argFiles = null;
    ps.genSubstitutedFile(pigIStream, pigOStream, arg, argFiles);
    FileInputStream pigResultStream = new FileInputStream(basedir + "/output1.pig");
    pigExResultStream = new FileInputStream(basedir + "/ExpectedResultCmdLnPriorDeclare.pig");
    compareResults(pigExResultStream, pigResultStream);
    log.info("Done");
}