Java Code Examples for java.nio.file.Files.newInputStream()

The following are Jave code examples for showing how to use newInputStream() of the java.nio.file.Files class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: powsybl-core   File: LoadFlowResultDeserializer.java   View Source Code Vote up 6 votes
public static LoadFlowResult read(Path jsonFile) {
    Objects.requireNonNull(jsonFile);
    try (InputStream is = Files.newInputStream(jsonFile)) {
        return read(is);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example 2
Project: openjdk-jdk10   File: ZeroDate.java   View Source Code Vote up 6 votes
public static void main(String[] args) throws Exception {
    // create a zip file, and read it in as a byte array
    Path path = Files.createTempFile("bad", ".zip");
    try (OutputStream os = Files.newOutputStream(path);
            ZipOutputStream zos = new ZipOutputStream(os)) {
        ZipEntry e = new ZipEntry("x");
        zos.putNextEntry(e);
        zos.write((int) 'x');
    }
    int len = (int) Files.size(path);
    byte[] data = new byte[len];
    try (InputStream is = Files.newInputStream(path)) {
        is.read(data);
    }
    Files.delete(path);

    // year, month, day are zero
    testDate(data.clone(), 0, LocalDate.of(1979, 11, 30));
    // only year is zero
    testDate(data.clone(), 0 << 25 | 4 << 21 | 5 << 16, LocalDate.of(1980, 4, 5));
}
 
Example 3
Project: elasticsearch_my   File: GoogleCloudStorageService.java   View Source Code Vote up 6 votes
/**
 * HTTP request initializer that loads credentials from the service account file
 * and manages authentication for HTTP requests
 */
private GoogleCredential loadCredentials(String serviceAccount) throws IOException {
    if (serviceAccount == null) {
        throw new ElasticsearchException("Cannot load Google Cloud Storage service account file from a null path");
    }

    Path account = environment.configFile().resolve(serviceAccount);
    if (Files.exists(account) == false) {
        throw new ElasticsearchException("Unable to find service account file [" + serviceAccount
                + "] defined for repository");
    }

    try (InputStream is = Files.newInputStream(account)) {
        GoogleCredential credential = GoogleCredential.fromStream(is);
        if (credential.createScopedRequired()) {
            credential = credential.createScoped(Collections.singleton(StorageScopes.DEVSTORAGE_FULL_CONTROL));
        }
        return credential;
    }
}
 
Example 4
Project: oscm   File: EclipseProjectReader.java   View Source Code Vote up 6 votes
/**
 * Reads the path to the project from the Eclipse' .location meta data file.
 * This file can be found in
 * 'workspace\.metadata\.plugins\org.eclipse.core.resources\.projects\
 * PROJECTNAME\.lo c a t i o n ' .<br />
 * The .location files is written with a special Outpustream and read with
 * an special InputStream implementation. You can find them in the eclipse
 * project org.eclipse.core.resource. The class names are<br />
 * org.eclipse.core.internal.localstore.SafeChunkyInputStream and <br />
 * org.eclipse.core.internal.localstore.SafeChunkyOutputStream.
 * <p>
 * The eclipse implementation which reads the .location file can be found in
 * the same project, the class name is
 * org.eclipse.core.internal.resources.LocalMetaArea, refer to method
 * readPrivateDescription.
 * <p>
 * Basically the first 16 bytes of the .location file are for consistency
 * reason there, the next bytes are the path to the project source. Those
 * bytes must be read via DataInputStream.readUTF.
 */
private String readFromLocationFile(File project) throws IOException {
    String result = "";
    Path location = Paths.get(project.getAbsolutePath())
            .resolve(".location");
    InputStream inputStream = Files.newInputStream(location);
    try (DataInputStream dataStream = new DataInputStream(inputStream);) {
        byte[] begin_chunk = new byte[16];
        dataStream.read(begin_chunk, 0, 16);
        result = dataStream.readUTF();

        String uriPrefix = "URI//file:";
        if (System.getProperty("os.name").startsWith("Windows")) {
            uriPrefix = uriPrefix.concat("/");
        }

        if (result.startsWith(uriPrefix)) {
            result = result.substring(uriPrefix.length());
        }
    }
    return result;
}
 
Example 5
Project: incubator-netbeans   File: NbinstURLStreamHandler.java   View Source Code Vote up 5 votes
public InputStream getInputStream() throws IOException {
    this.connect();
    if (iStream == null) {
        try {
            iStream = Files.newInputStream(f.toPath());
        } catch (InvalidPathException ex) {
            throw new IOException(ex);
        }
    }
    return iStream;
}
 
Example 6
Project: openjdk-jdk10   File: XPathTest.java   View Source Code Vote up 5 votes
/**
 * XPath.evaluate(java.lang.String expression, InputSource source,
 * QName returnType) return correct number value if return type is Number.
 *
 * @throws Exception If any errors occur.
 */
@Test
public void testCheckXPath36() throws Exception {
    try (InputStream is = Files.newInputStream(XML_PATH)) {
        assertEquals(xpath.evaluate(EXPRESSION_NAME_A, new InputSource(is),
            NUMBER), 6d);
    }
}
 
Example 7
Project: elasticsearch_my   File: FileTestUtils.java   View Source Code Vote up 5 votes
/**
 * Unzip a zip file to a destination directory.  If the zip file does not exist, an IOException is thrown.
 * If the destination directory does not exist, it will be created.
 *
 * @param zip      zip file to unzip
 * @param destDir  directory to unzip the file to
 * @param prefixToRemove  the (optional) prefix in the zip file path to remove when writing to the destination directory
 * @throws IOException if zip file does not exist, or there was an error reading from the zip file or
 *                     writing to the destination directory
 */
public static void unzip(final Path zip, final Path destDir, @Nullable final String prefixToRemove) throws IOException {
    if (Files.notExists(zip)) {
        throw new IOException("[" + zip + "] zip file must exist");
    }
    Files.createDirectories(destDir);

    try (ZipInputStream zipInput = new ZipInputStream(Files.newInputStream(zip))) {
        ZipEntry entry;
        while ((entry = zipInput.getNextEntry()) != null) {
            final String entryPath;
            if (prefixToRemove != null) {
                if (entry.getName().startsWith(prefixToRemove)) {
                    entryPath = entry.getName().substring(prefixToRemove.length());
                } else {
                    throw new IOException("prefix not found: " + prefixToRemove);
                }
            } else {
                entryPath = entry.getName();
            }
            final Path path = Paths.get(destDir.toString(), entryPath);
            if (entry.isDirectory()) {
                Files.createDirectories(path);
            } else {
                Files.copy(zipInput, path);
            }
            zipInput.closeEntry();
        }
    }
}
 
Example 8
Project: PiCameraProject   File: App.java   View Source Code Vote up 5 votes
private static Properties initialize() {
    final Properties retval = new Properties();
    final Path path = Paths.get("config.properties");
    try(InputStream in = Files.newInputStream(path)){
        retval.load(in);
    } catch (IOException ex) {
        Logger.getLogger(App.class.getName()).log(Level.SEVERE, "Unable to read config", ex);
    }
    return retval;
}
 
Example 9
Project: powsybl-core   File: NetworkXml.java   View Source Code Vote up 5 votes
static void validate(Path file) {
    try (InputStream is = Files.newInputStream(file)) {
        validate(is);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example 10
Project: xtf   File: XTFKeyStore.java   View Source Code Vote up 5 votes
public static XTFKeyStore getInstance() {
	if (instance == null) {
		Path defaultKeystore = findDefaultKeyStore();
		try (InputStream is = Files.newInputStream(defaultKeystore)) {
			instance = newInstance(is, "");
		} catch (IOException ex) {
			throw new RuntimeException("Couldn't load default keystore: " + defaultKeystore, ex);
		}
	}

	return instance;
}
 
Example 11
Project: ArchUnit   File: ClassFileSource.java   View Source Code Vote up 5 votes
private Supplier<InputStream> newInputStreamSupplierFor(final Path file) {
    return new InputStreamSupplier() {
        @Override
        InputStream getInputStream() throws IOException {
            return Files.newInputStream(file);
        }
    };
}
 
Example 12
Project: openjdk-jdk10   File: AddPackagesAttribute.java   View Source Code Vote up 5 votes
static void addPackagesAttribute(Path mi, Set<String> packages) throws IOException {
    byte[] bytes;
    try (InputStream in = Files.newInputStream(mi)) {
        ModuleInfoExtender extender = ModuleInfoExtender.newExtender(in);
        extender.packages(packages);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        extender.write(baos);
        bytes = baos.toByteArray();
    }

    Files.write(mi, bytes);
}
 
Example 13
Project: powsybl-core   File: NetworkXml.java   View Source Code Vote up 5 votes
public static void update(Network network, Path xmlFile) {
    try (InputStream is = Files.newInputStream(xmlFile)) {
        update(network, is);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
}
 
Example 14
Project: EpiStats   File: DataCollection.java   View Source Code Vote up 5 votes
public static DataCollection read(Path file) throws IOException {
	if (!Files.exists(file))
		throw new FileNotFoundException(file.getFileName().toString());

	try (DataInputStream in = new DataInputStream(Files.newInputStream(file))) {
		return read(in);
	}
}
 
Example 15
Project: maven-archetype-springboot   File: CsvUtils.java   View Source Code Vote up 5 votes
@SneakyThrows(IOException.class)
public static List<String[]> toList(Path file) {
    try (InputStream is = Files.newInputStream(file, READ)) {
        CsvParserSettings settings = Csv.parseExcel();
        settings.setHeaderExtractionEnabled(true);
        CsvParser parser = new CsvParser(settings);
        return parser.parseAll(is);
    }
}
 
Example 16
Project: httrack2warc   File: HttrackCrawl.java   View Source Code Vote up 5 votes
private void parseDoitLog() throws IOException {
    try (InputStream stream = Files.newInputStream(dir.resolve("hts-cache/doit.log"))) {
        HtsDoitParser doitLog = new HtsDoitParser(stream);
        launchTime = doitLog.crawlStartTime;
        outputDir = doitLog.outputDir;
        httrackOptions = doitLog.commandLine;
    }
}
 
Example 17
Project: incubator-netbeans   File: NBJRTURLStreamHandler.java   View Source Code Vote up 5 votes
@Override
public InputStream getInputStream() throws IOException {
    connect();
    final Path _path = path;
    if (_path == null) {
        throw new IOException(String.format(
            "Cannot resolve: %s",   //NOI18N
            getURL()));
    }
    return Files.newInputStream(path);
}
 
Example 18
Project: httrack2warc   File: HttrackCrawl.java   View Source Code Vote up 5 votes
private void parseHtsLog() throws IOException {
    for (String file: LOG_FILE_NAMES) {
        try (HtsLogParser htsLog = new HtsLogParser(Files.newInputStream(dir.resolve(file)))) {
            httrackVersion = htsLog.version;
            return;
        } catch (NoSuchFileException e) {
            // try next
        }
    }

}
 
Example 19
Project: cf-mta-deploy-service   File: FileSplitter.java   View Source Code Vote up 4 votes
public FileSplitter(Path filePath) throws IOException {
    this(filePath.getFileName().toString(), filePath.toAbsolutePath().toString(), Files.newInputStream(filePath), null);
    this.fileSize = Files.size(filePath);
}
 
Example 20
Project: openjdk-jdk10   File: ModuleTargetHelper.java   View Source Code Vote up 4 votes
public static ModuleTarget getJavaBaseTarget() throws IOException {
    Path p = Paths.get(URI.create("jrt:/modules/java.base/module-info.class"));
    try (InputStream in = Files.newInputStream(p)) {
        return read(in);
    }
}