Java Code Examples for java.io.OutputStream#close()
The following examples show how to use
java.io.OutputStream#close() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Rclone.java From rcloneExplorer with MIT License | 6 votes |
public void exportConfigFile(Uri uri) throws IOException { File configFile = new File(rcloneConf); Uri config = Uri.fromFile(configFile); InputStream inputStream = context.getContentResolver().openInputStream(config); OutputStream outputStream = context.getContentResolver().openOutputStream(uri); if (inputStream == null || outputStream == null) { return; } byte[] buffer = new byte[4096]; int offset; while ((offset = inputStream.read(buffer)) > 0) { outputStream.write(buffer, 0, offset); } inputStream.close(); outputStream.flush(); outputStream.close(); }
Example 2
Source File: FileUtils.java From directory-ldap-api with Apache License 2.0 | 6 votes |
/** * Writes a String to a file creating the file if it does not exist. * * @param file the file to write * @param data the content to write to the file * @param encoding the encoding to use, {@code null} means platform default * @param append if {@code true}, then the String will be added to the * end of the file rather than overwriting * @throws IOException in case of an I/O error * @since 2.3 */ public static void writeStringToFile( File file, String data, Charset encoding, boolean append ) throws IOException { OutputStream out = null; try { out = openOutputStream( file, append ); IOUtils.write( data, out, encoding ); out.close(); // don't swallow close Exception if copy completes normally } finally { IOUtils.closeQuietly( out ); } }
Example 3
Source File: Main.java From hiped2 with Apache License 2.0 | 6 votes |
public static int createInputFile(Path file, Path targetFile) throws IOException { Configuration conf = new Configuration(); FileSystem fs = file.getFileSystem(conf); int numNodes = getNumNodes(file); double initialPageRank = 1.0 / (double) numNodes; OutputStream os = fs.create(targetFile); LineIterator iter = IOUtils .lineIterator(fs.open(file), "UTF8"); while (iter.hasNext()) { String line = iter.nextLine(); String[] parts = StringUtils.split(line); Node node = new Node() .setPageRank(initialPageRank) .setAdjacentNodeNames( Arrays.copyOfRange(parts, 1, parts.length)); IOUtils.write(parts[0] + '\t' + node.toString() + '\n', os); } os.close(); return numNodes; }
Example 4
Source File: PostOnDelete.java From jdk8u-jdk with GNU General Public License v2.0 | 6 votes |
@Override public void handle(HttpExchange exchange) throws IOException { String requestMethod = exchange.getRequestMethod(); if (requestMethod.equalsIgnoreCase("DELETE")) { InputStream is = exchange.getRequestBody(); int count = 0; while (is.read() != -1) { count++; } is.close(); Headers responseHeaders = exchange.getResponseHeaders(); responseHeaders.set("Content-Type", "text/plain"); exchange.sendResponseHeaders((count == len) ? 200 : 400, 0); OutputStream os = exchange.getResponseBody(); String str = "Hello from server!"; os.write(str.getBytes()); os.flush(); os.close(); } }
Example 5
Source File: TestUtils.java From grpc-nebula-java with Apache License 2.0 | 6 votes |
/** * Saves a file from the classpath resources in src/main/resources/certs as a file on the * filesystem. * * @param name name of a file in src/main/resources/certs. */ public static File loadCert(String name) throws IOException { InputStream in = new BufferedInputStream(TestUtils.class.getResourceAsStream("/certs/" + name)); File tmpFile = File.createTempFile(name, ""); tmpFile.deleteOnExit(); OutputStream os = new BufferedOutputStream(new FileOutputStream(tmpFile)); try { int b; while ((b = in.read()) != -1) { os.write(b); } os.flush(); } finally { in.close(); os.close(); } return tmpFile; }
Example 6
Source File: SocketTest.java From j2objc with Apache License 2.0 | 6 votes |
public void testWriteAfterClose() throws Exception { MockServer server = new MockServer(); server.enqueue(new byte[0], 3); Socket socket = new Socket("localhost", server.port); OutputStream out = socket.getOutputStream(); out.write(5); out.write(3); socket.close(); out.close(); try { out.write(9); fail(); } catch (IOException expected) { } server.shutdown(); }
Example 7
Source File: AbstractReportGenerator.java From pentaho-reporting with GNU Lesser General Public License v2.1 | 6 votes |
/** * Generates the report in the specified <code>outputType</code> and writes it into the specified * <code>outputFile</code>. * * @param outputType the output type of the report (HTML, PDF, HTML) * @param outputFile the file into which the report will be written * @throws IllegalArgumentException indicates the required parameters were not provided * @throws IOException indicates an error opening the file for writing * @throws ReportProcessingException indicates an error generating the report */ public void generateReport( final OutputType outputType, File outputFile ) throws IllegalArgumentException, IOException, ReportProcessingException { if ( outputFile == null ) { throw new IllegalArgumentException( "The output file was not specified" ); } OutputStream outputStream = null; try { // Open the output stream outputStream = new BufferedOutputStream( new FileOutputStream( outputFile ) ); // Generate the report to this output stream generateReport( outputType, outputStream ); } finally { if ( outputStream != null ) { outputStream.close(); } } }
Example 8
Source File: GoogleStorageReadFeatureTest.java From cyberduck with GNU General Public License v3.0 | 6 votes |
@Test public void testReadWhitespace() throws Exception { final int length = 47; final byte[] content = RandomUtils.nextBytes(length); final Path container = new Path("test.cyberduck.ch", EnumSet.of(Path.Type.directory, Path.Type.volume)); final Path file = new Path(container, String.format("t %s", new AlphanumericRandomStringService().random()), EnumSet.of(Path.Type.file)); final TransferStatus status = new TransferStatus().length(content.length); status.setChecksum(new SHA256ChecksumCompute().compute(new ByteArrayInputStream(content), status)); final OutputStream out = new GoogleStorageWriteFeature(session).write(file, status, new DisabledConnectionCallback()); new StreamCopier(new TransferStatus(), new TransferStatus()).transfer(new ByteArrayInputStream(content), out); out.close(); assertEquals(length, new GoogleStorageAttributesFinderFeature(session).find(file).getSize()); final CountingInputStream in = new CountingInputStream(new GoogleStorageReadFeature(session).read(file, new TransferStatus(), new DisabledConnectionCallback())); in.close(); assertEquals(0L, in.getByteCount(), 0L); new GoogleStorageDeleteFeature(session).delete(Collections.singletonList(file), new DisabledLoginCallback(), new Delete.DisabledCallback()); }
Example 9
Source File: DropboxReadFeatureTest.java From cyberduck with GNU General Public License v3.0 | 5 votes |
@Test public void testReadRange() throws Exception { final Path drive = new DropboxHomeFinderFeature(session).find(); final Path test = new Path(drive, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file)); new DropboxTouchFeature(session).touch(test, new TransferStatus()); final Local local = new Local(System.getProperty("java.io.tmpdir"), new AlphanumericRandomStringService().random()); final byte[] content = RandomUtils.nextBytes(1000); final OutputStream out = local.getOutputStream(false); assertNotNull(out); IOUtils.write(content, out); out.close(); new DefaultUploadFeature<String>(new DropboxWriteFeature(session)).upload( test, local, new BandwidthThrottle(BandwidthThrottle.UNLIMITED), new DisabledStreamListener(), new TransferStatus().length(content.length), new DisabledConnectionCallback()); final TransferStatus status = new TransferStatus(); status.setLength(content.length); status.setAppend(true); status.setOffset(100L); final DropboxReadFeature read = new DropboxReadFeature(session); assertTrue(read.offset(test)); final InputStream in = read.read(test, status.length(content.length - 100), new DisabledConnectionCallback()); assertNotNull(in); final ByteArrayOutputStream buffer = new ByteArrayOutputStream(content.length - 100); new StreamCopier(status, status).transfer(in, buffer); final byte[] reference = new byte[content.length - 100]; System.arraycopy(content, 100, reference, 0, content.length - 100); assertArrayEquals(reference, buffer.toByteArray()); in.close(); new DropboxDeleteFeature(session).delete(Collections.singletonList(test), new DisabledLoginCallback(), new Delete.DisabledCallback()); }
Example 10
Source File: SimpleDiskCache.java From Reservoir with MIT License | 5 votes |
private void closeQuietly(OutputStream output) { try { if (output != null) { output.close(); } } catch (IOException ioe) { // ignore } }
Example 11
Source File: VfsFileTests.java From xodus with Apache License 2.0 | 5 votes |
@Test public void testDeleteFile3() throws IOException { final Transaction txn = env.beginTransaction(); for (int i = 0; i < 10; ++i) { final File file0 = vfs.createFile(txn, "file0"); final OutputStream outputStream = vfs.writeFile(txn, file0); outputStream.write("vain bytes to be deleted".getBytes()); outputStream.close(); txn.flush(); Assert.assertNotNull(vfs.deleteFile(txn, "file0")); txn.flush(); } Assert.assertEquals(0L, vfs.getContents().count(txn)); txn.commit(); }
Example 12
Source File: ExifInterface.java From Camera2 with Apache License 2.0 | 5 votes |
/** * Writes the tags from this ExifInterface object into a jpeg compressed * bitmap, removing prior exif tags. * * @param bmap a bitmap to compress and write exif into. * @param exifOutFileName a String containing the filepath to which the jpeg * image with added exif tags will be written. * @throws FileNotFoundException * @throws IOException */ public void writeExif(Bitmap bmap, String exifOutFileName) throws FileNotFoundException, IOException { if (bmap == null || exifOutFileName == null) { throw new IllegalArgumentException(NULL_ARGUMENT_STRING); } OutputStream s = null; s = getExifWriterStream(exifOutFileName); bmap.compress(Bitmap.CompressFormat.JPEG, 90, s); s.flush(); s.close(); }
Example 13
Source File: AbstractMarshallerImpl.java From openjdk-8-source with GNU General Public License v2.0 | 5 votes |
public void marshal(Object jaxbElement, File output) throws JAXBException { checkNotNull(jaxbElement, "jaxbElement", output, "output" ); try { OutputStream os = new BufferedOutputStream(new FileOutputStream(output)); try { marshal( jaxbElement, new StreamResult(os) ); } finally { os.close(); } } catch (IOException e) { throw new JAXBException(e); } }
Example 14
Source File: Resources.java From opencensus-java with Apache License 2.0 | 5 votes |
/** * Returns a resource of the given name as a temporary file. * * @param resourceName name of the resource * @return a temporary {@link File} containing a copy of the resource * @throws FileNotFoundException if no resource of the given name is found * @throws IOException if an I/O error occurs */ static File getResourceAsTempFile(String resourceName) throws IOException { checkArgument(!Strings.isNullOrEmpty(resourceName), "resourceName"); File file = File.createTempFile(resourceName, ".tmp"); OutputStream os = new FileOutputStream(file); try { getResourceAsTempFile(resourceName, file, os); return file; } finally { os.close(); } }
Example 15
Source File: ResponseDownloadPerformer.java From lastaflute with Apache License 2.0 | 5 votes |
protected void closeDownloadStream(OutputStream out) throws IOException { try { out.close(); } catch (IOException e) { throwDownloadIOException(e); } }
Example 16
Source File: TestFileSystem.java From RDFS with Apache License 2.0 | 5 votes |
public void map(UTF8 key, LongWritable value, OutputCollector<UTF8, LongWritable> collector, Reporter reporter) throws IOException { String name = key.toString(); long size = value.get(); long seed = Long.parseLong(name); random.setSeed(seed); reporter.setStatus("creating " + name); // write to temp file initially to permit parallel execution Path tempFile = new Path(DATA_DIR, name+suffix); OutputStream out = fs.create(tempFile); long written = 0; try { while (written < size) { if (fastCheck) { Arrays.fill(buffer, (byte)random.nextInt(Byte.MAX_VALUE)); } else { random.nextBytes(buffer); } long remains = size - written; int length = (remains<=buffer.length) ? (int)remains : buffer.length; out.write(buffer, 0, length); written += length; reporter.setStatus("writing "+name+"@"+written+"/"+size); } } finally { out.close(); } // rename to final location fs.rename(tempFile, new Path(DATA_DIR, name)); collector.collect(new UTF8("bytes"), new LongWritable(written)); reporter.setStatus("wrote " + name); }
Example 17
Source File: ConnectionMethodsTest.java From gemfirexd-oss with Apache License 2.0 | 4 votes |
/** * Test the createBlob method implementation in the Connection interface * * @exception SQLException, FileNotFoundException, Exception if error occurs */ public void testCreateBlob() throws SQLException, FileNotFoundException, IOException, Exception{ Connection conn = getConnection(); int b, c; Blob blob; Statement s = createStatement(); PreparedStatement ps = prepareStatement("insert into blobtable2 (n, blobcol)" + " values(?,?)"); ps.setInt(1,1000); blob = conn.createBlob(); try { is = (FileInputStream) AccessController.doPrivileged( new PrivilegedExceptionAction() { public Object run() throws FileNotFoundException { return new FileInputStream("extin/short.txt"); } }); } catch (PrivilegedActionException e) { // e.getException() should be an instance of FileNotFoundException, // as only "checked" exceptions will be "wrapped" in a // PrivilegedActionException. throw (FileNotFoundException) e.getException(); } OutputStream os = blob.setBinaryStream(1); ArrayList beforeUpdateList = new ArrayList(); int actualLength = 0; c = is.read(); while(c>0) { os.write(c); beforeUpdateList.add(c); c = is.read(); actualLength ++; } ps.setBlob(2, blob); ps.executeUpdate(); Statement stmt = createStatement(); ResultSet rs = stmt.executeQuery("select blobcol from blobtable2 where n = 1000"); assertTrue(rs.next()); blob = rs.getBlob(1); assertEquals(beforeUpdateList.size(), blob.length()); //Get the InputStream from this Blob. InputStream in = blob.getBinaryStream(); ArrayList afterUpdateList = new ArrayList(); b = in.read(); while (b > -1) { afterUpdateList.add(b); b = in.read(); } assertEquals(beforeUpdateList.size(), afterUpdateList.size()); //Now check if the two InputStreams //match for (int i = 0; i < blob.length(); i++) { assertEquals(beforeUpdateList.get(i), afterUpdateList.get(i)); } os.close(); is.close(); }
Example 18
Source File: SimpleMetaStoreTests.java From orion.server with Eclipse Public License 1.0 | 4 votes |
@Test public void testMoveSimpleProject() throws CoreException { // create the MetaStore IMetaStore metaStore = OrionConfiguration.getMetaStore(); // create the user UserInfo userInfo = new UserInfo(); userInfo.setUserName(testUserLogin); userInfo.setFullName(testUserLogin); metaStore.createUser(userInfo); // create the workspace String workspaceName = SimpleMetaStore.DEFAULT_WORKSPACE_NAME; WorkspaceInfo workspaceInfo = new WorkspaceInfo(); workspaceInfo.setFullName(workspaceName); workspaceInfo.setUserId(userInfo.getUniqueId()); metaStore.createWorkspace(workspaceInfo); // create the project String projectName = "Orion Project"; ProjectInfo projectInfo = new ProjectInfo(); projectInfo.setFullName(projectName); projectInfo.setWorkspaceId(workspaceInfo.getUniqueId()); metaStore.createProject(projectInfo); // create a project directory and file IFileStore projectFolder = metaStore.getDefaultContentLocation(projectInfo); if (!projectFolder.fetchInfo().exists()) { projectFolder.mkdir(EFS.NONE, null); } assertTrue(projectFolder.fetchInfo().exists()); assertTrue(projectFolder.fetchInfo().isDirectory()); String fileName = "file.html"; IFileStore file = projectFolder.getChild(fileName); try { OutputStream outputStream = file.openOutputStream(EFS.NONE, null); outputStream.write("<!doctype html>".getBytes()); outputStream.close(); } catch (IOException e) { fail("Count not create a test file in the Orion Project:" + e.getLocalizedMessage()); } assertTrue("the file in the project folder should exist.", file.fetchInfo().exists()); // update the project with the content location projectInfo.setContentLocation(projectFolder.toLocalFile(EFS.NONE, null).toURI()); metaStore.updateProject(projectInfo); // move the project by renaming the project by changing the projectName String movedProjectName = "Moved Orion Project"; projectInfo.setFullName(movedProjectName); // update the project metaStore.updateProject(projectInfo); // read the project back again ProjectInfo readProjectInfo = metaStore.readProject(workspaceInfo.getUniqueId(), projectInfo.getFullName()); assertNotNull(readProjectInfo); assertTrue(readProjectInfo.getFullName().equals(movedProjectName)); // verify the local project has moved IFileStore workspaceFolder = metaStore.getWorkspaceContentLocation(workspaceInfo.getUniqueId()); projectFolder = workspaceFolder.getChild(projectName); assertFalse("the original project folder should not exist.", projectFolder.fetchInfo().exists()); projectFolder = workspaceFolder.getChild(movedProjectName); assertTrue("the new project folder should exist.", projectFolder.fetchInfo().exists() && projectFolder.fetchInfo().isDirectory()); file = projectFolder.getChild(fileName); assertTrue("the file in the project folder should exist.", file.fetchInfo().exists()); assertEquals("The ContentLocation should have been updated.", projectFolder.toLocalFile(EFS.NONE, null).toURI(), projectInfo.getContentLocation()); // delete the project contents file.delete(EFS.NONE, null); assertFalse("the file in the project folder should not exist.", file.fetchInfo().exists()); }
Example 19
Source File: CloseStream.java From spotbugs with GNU Lesser General Public License v2.1 | 4 votes |
public static void writeFile(File f, Object o) throws IOException { OutputStream out = new FileOutputStream(f); int i = o.hashCode(); out.close(); }
Example 20
Source File: BinaryPropertyListWriter.java From Alite with GNU General Public License v3.0 | 2 votes |
/** * Writes a binary plist file with the given object as the root. * * @param file the file to write to * @param root the source of the data to write to the file * @throws IOException When an IO error occurs while writing to the file or the object structure contains * data that cannot be saved. */ public static void write(File file, NSObject root) throws IOException { OutputStream out = new FileOutputStream(file); write(out, root); out.close(); }