Java Code Examples for libcore.io.IoUtils

The following examples show how to use libcore.io.IoUtils. These examples are extracted from open source projects. 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 Project: AndroidComponentPlugin   Source File: DexPathList.java    License: Apache License 2.0 6 votes vote down vote up
public String findNativeLibrary(String name) {
    maybeInit();

    if (isDirectory) {
        String path = new File(dir, name).getPath();
        if (IoUtils.canOpenReadOnly(path)) {
            return path;
        }
    } else if (urlHandler != null) {
        // Having a urlHandler means the element has a zip file.
        // In this case Android supports loading the library iff
        // it is stored in the zip uncompressed.

        String entryName = new File(dir, name).getPath();
        if (urlHandler.isEntryStored(entryName)) {
          return zip.getPath() + zipSeparator + entryName;
        }
    }

    return null;
}
 
Example 2
Source Project: AndroidComponentPlugin   Source File: DexPathList.java    License: Apache License 2.0 6 votes vote down vote up
public String findNativeLibrary(String name) {
    maybeInit();

    if (zipDir == null) {
        String entryPath = new File(path, name).getPath();
        if (IoUtils.canOpenReadOnly(entryPath)) {
            return entryPath;
        }
    } else if (urlHandler != null) {
        // Having a urlHandler means the element has a zip file.
        // In this case Android supports loading the library iff
        // it is stored in the zip uncompressed.
        String entryName = zipDir + '/' + name;
        if (urlHandler.isEntryStored(entryName)) {
          return path.getPath() + zipSeparator + entryName;
        }
    }

    return null;
}
 
Example 3
Source Project: AndroidComponentPlugin   Source File: DexPathList.java    License: Apache License 2.0 6 votes vote down vote up
public String findNativeLibrary(String name) {
    maybeInit();

    if (isDirectory) {
        String path = new File(dir, name).getPath();
        if (IoUtils.canOpenReadOnly(path)) {
            return path;
        }
    } else if (zipFile != null) {
        String entryName = new File(dir, name).getPath();
        if (isZipEntryExistsAndStored(zipFile, entryName)) {
          return zip.getPath() + zipSeparator + entryName;
        }
    }

    return null;
}
 
Example 4
Source Project: AndroidComponentPlugin   Source File: DexPathList.java    License: Apache License 2.0 6 votes vote down vote up
public String findNativeLibrary(String name) {
    maybeInit();

    if (zipDir == null) {
        String entryPath = new File(path, name).getPath();
        if (IoUtils.canOpenReadOnly(entryPath)) {
            return entryPath;
        }
    } else if (urlHandler != null) {
        // Having a urlHandler means the element has a zip file.
        // In this case Android supports loading the library iff
        // it is stored in the zip uncompressed.
        String entryName = zipDir + '/' + name;
        if (urlHandler.isEntryStored(entryName)) {
          return path.getPath() + zipSeparator + entryName;
        }
    }

    return null;
}
 
Example 5
Source Project: j2objc   Source File: File.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Creates a new, empty file on the file system according to the path
 * information stored in this file. This method returns true if it creates
 * a file, false if the file already existed. Note that it returns false
 * even if the file is not a file (because it's a directory, say).
 *
 * <p>This method is not generally useful. For creating temporary files,
 * use {@link #createTempFile} instead. For reading/writing files, use {@link FileInputStream},
 * {@link FileOutputStream}, or {@link RandomAccessFile}, all of which can create files.
 *
 * <p>Note that this method does <i>not</i> throw {@code IOException} if the file
 * already exists, even if it's not a regular file. Callers should always check the
 * return value, and may additionally want to call {@link #isFile}.
 *
 * @return true if the file has been created, false if it
 *         already exists.
 * @throws IOException if it's not possible to create the file.
 */
public boolean createNewFile() throws IOException {
    if (0 == path.length()) {
        throw new IOException("No such file or directory");
    }
    if (isDirectory()) {  // true for paths like "dir/..", which can't be files.
        throw new IOException("Cannot create: " + path);
    }
    FileDescriptor fd = null;
    try {
        // On Android, we don't want default permissions to allow global access.
        fd = Libcore.os.open(path, O_RDWR | O_CREAT | O_EXCL, 0600);
        return true;
    } catch (ErrnoException errnoException) {
        if (errnoException.errno == EEXIST) {
            // The file already exists.
            return false;
        }
        throw errnoException.rethrowAsIOException();
    } finally {
        IoUtils.close(fd); // TODO: should we suppress IOExceptions thrown here?
    }
}
 
Example 6
Source Project: AndroidComponentPlugin   Source File: DexPathList.java    License: Apache License 2.0 6 votes vote down vote up
public String findNativeLibrary(String name) {
    maybeInit();

    if (zipDir == null) {
        String entryPath = new File(path, name).getPath();
        if (IoUtils.canOpenReadOnly(entryPath)) {
            return entryPath;
        }
    } else if (urlHandler != null) {
        // Having a urlHandler means the element has a zip file.
        // In this case Android supports loading the library iff
        // it is stored in the zip uncompressed.
        String entryName = zipDir + '/' + name;
        if (urlHandler.isEntryStored(entryName)) {
          return path.getPath() + zipSeparator + entryName;
        }
    }

    return null;
}
 
Example 7
Source Project: AndroidComponentPlugin   Source File: DexPathList.java    License: Apache License 2.0 6 votes vote down vote up
public String findNativeLibrary(String name) {
    maybeInit();

    if (isDirectory) {
        String path = new File(dir, name).getPath();
        if (IoUtils.canOpenReadOnly(path)) {
            return path;
        }
    } else if (urlHandler != null) {
        // Having a urlHandler means the element has a zip file.
        // In this case Android supports loading the library iff
        // it is stored in the zip uncompressed.

        String entryName = new File(dir, name).getPath();
        if (urlHandler.isEntryStored(entryName)) {
          return zip.getPath() + zipSeparator + entryName;
        }
    }

    return null;
}
 
Example 8
Source Project: android_9.0.0_r45   Source File: BrightnessTracker.java    License: Apache License 2.0 6 votes vote down vote up
private void readEvents() {
    synchronized (mEventsLock) {
        // Read might prune events so mark as dirty.
        mEventsDirty = true;
        mEvents.clear();
        final AtomicFile readFrom = mInjector.getFile(EVENTS_FILE);
        if (readFrom != null && readFrom.exists()) {
            FileInputStream input = null;
            try {
                input = readFrom.openRead();
                readEventsLocked(input);
            } catch (IOException e) {
                readFrom.delete();
                Slog.e(TAG, "Failed to read change mEvents.", e);
            } finally {
                IoUtils.closeQuietly(input);
            }
        }
    }
}
 
Example 9
Source Project: android_9.0.0_r45   Source File: BrightnessTracker.java    License: Apache License 2.0 6 votes vote down vote up
private void readAmbientBrightnessStats() {
    mAmbientBrightnessStatsTracker = new AmbientBrightnessStatsTracker(mUserManager, null);
    final AtomicFile readFrom = mInjector.getFile(AMBIENT_BRIGHTNESS_STATS_FILE);
    if (readFrom != null && readFrom.exists()) {
        FileInputStream input = null;
        try {
            input = readFrom.openRead();
            mAmbientBrightnessStatsTracker.readStats(input);
        } catch (IOException e) {
            readFrom.delete();
            Slog.e(TAG, "Failed to read ambient brightness stats.", e);
        } finally {
            IoUtils.closeQuietly(input);
        }
    }
}
 
Example 10
Source Project: android_9.0.0_r45   Source File: ArtManagerService.java    License: Apache License 2.0 6 votes vote down vote up
private void postSuccess(String packageName, ParcelFileDescriptor fd,
        ISnapshotRuntimeProfileCallback callback) {
    if (DEBUG) {
        Slog.d(TAG, "Successfully snapshot profile for " + packageName);
    }
    mHandler.post(() -> {
        try {
            // Double check that the descriptor is still valid.
            // We've seen production issues (b/76028139) where this can turn invalid (there are
            // suspicions around the finalizer behaviour).
            if (fd.getFileDescriptor().valid()) {
                callback.onSuccess(fd);
            } else {
                Slog.wtf(TAG, "The snapshot FD became invalid before posting the result for "
                        + packageName);
                callback.onError(ArtManager.SNAPSHOT_FAILED_INTERNAL_ERROR);
            }
        } catch (Exception e) {
            Slog.w(TAG,
                    "Failed to call onSuccess after profile snapshot for " + packageName, e);
        } finally {
            IoUtils.closeQuietly(fd);
        }
    });
}
 
Example 11
Source Project: android_9.0.0_r45   Source File: UserManagerService.java    License: Apache License 2.0 6 votes vote down vote up
private UserData readUserLP(int id) {
    FileInputStream fis = null;
    try {
        AtomicFile userFile =
                new AtomicFile(new File(mUsersDir, Integer.toString(id) + XML_SUFFIX));
        fis = userFile.openRead();
        return readUserLP(id, fis);
    } catch (IOException ioe) {
        Slog.e(LOG_TAG, "Error reading user list");
    } catch (XmlPullParserException pe) {
        Slog.e(LOG_TAG, "Error reading user list");
    } finally {
        IoUtils.closeQuietly(fis);
    }
    return null;
}
 
Example 12
Source Project: android_9.0.0_r45   Source File: PackageInstallerSession.java    License: Apache License 2.0 6 votes vote down vote up
private static void extractNativeLibraries(File packageDir, String abiOverride, boolean inherit)
        throws PackageManagerException {
    final File libDir = new File(packageDir, NativeLibraryHelper.LIB_DIR_NAME);
    if (!inherit) {
        // Start from a clean slate
        NativeLibraryHelper.removeNativeBinariesFromDirLI(libDir, true);
    }

    NativeLibraryHelper.Handle handle = null;
    try {
        handle = NativeLibraryHelper.Handle.create(packageDir);
        final int res = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libDir,
                abiOverride);
        if (res != PackageManager.INSTALL_SUCCEEDED) {
            throw new PackageManagerException(res,
                    "Failed to extract native libraries, res=" + res);
        }
    } catch (IOException e) {
        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
                "Failed to extract native libraries", e);
    } finally {
        IoUtils.closeQuietly(handle);
    }
}
 
Example 13
Source Project: android_9.0.0_r45   Source File: InstantAppRegistry.java    License: Apache License 2.0 6 votes vote down vote up
public byte[] getInstantAppCookieLPw(@NonNull String packageName,
        @UserIdInt int userId) {
    // Only installed packages can get their own cookie
    PackageParser.Package pkg = mService.mPackages.get(packageName);
    if (pkg == null) {
        return null;
    }

    byte[] pendingCookie = mCookiePersistence.getPendingPersistCookieLPr(pkg, userId);
    if (pendingCookie != null) {
        return pendingCookie;
    }
    File cookieFile = peekInstantCookieFile(packageName, userId);
    if (cookieFile != null && cookieFile.exists()) {
        try {
            return IoUtils.readFileAsByteArray(cookieFile.toString());
        } catch (IOException e) {
            Slog.w(LOG_TAG, "Error reading cookie file: " + cookieFile);
        }
    }
    return null;
}
 
Example 14
private int doRemoveSplit(int sessionId, String splitName, boolean logSuccess)
        throws RemoteException {
    final PrintWriter pw = getOutPrintWriter();
    PackageInstaller.Session session = null;
    try {
        session = new PackageInstaller.Session(
                mInterface.getPackageInstaller().openSession(sessionId));
        session.removeSplit(splitName);

        if (logSuccess) {
            pw.println("Success");
        }
        return 0;
    } catch (IOException e) {
        pw.println("Error: failed to remove split; " + e.getMessage());
        return 1;
    } finally {
        IoUtils.closeQuietly(session);
    }
}
 
Example 15
Source Project: android_9.0.0_r45   Source File: NetworkStatsRecorder.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Recover from {@link FileRotator} failure by dumping state to
 * {@link DropBoxManager} and deleting contents.
 */
private void recoverFromWtf() {
    if (DUMP_BEFORE_DELETE) {
        final ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            mRotator.dumpAll(os);
        } catch (IOException e) {
            // ignore partial contents
            os.reset();
        } finally {
            IoUtils.closeQuietly(os);
        }
        mDropBox.addData(TAG_NETSTATS_DUMP, os.toByteArray(), 0);
    }

    mRotator.deleteAll();
}
 
Example 16
Source Project: j2objc   Source File: FileOutputStream.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void close() throws IOException {
    guard.close();
    synchronized (this) {
        if (channel != null) {
            channel.close();
        }
        if (shouldClose) {
            IoUtils.close(fd);
        } else {
            // An owned fd has been invalidated by IoUtils.close, but
            // we need to explicitly stop using an unowned fd (http://b/4361076).
            fd = new FileDescriptor();
        }
    }
}
 
Example 17
Source Project: android_9.0.0_r45   Source File: AppFuseBridge.java    License: Apache License 2.0 6 votes vote down vote up
public ParcelFileDescriptor addBridge(MountScope mountScope)
        throws FuseUnavailableMountException, NativeDaemonConnectorException {
    try {
        synchronized (this) {
            Preconditions.checkArgument(mScopes.indexOfKey(mountScope.mountId) < 0);
            if (mNativeLoop == 0) {
                throw new FuseUnavailableMountException(mountScope.mountId);
            }
            final int fd = native_add_bridge(
                    mNativeLoop, mountScope.mountId, mountScope.open().detachFd());
            if (fd == -1) {
                throw new FuseUnavailableMountException(mountScope.mountId);
            }
            final ParcelFileDescriptor result = ParcelFileDescriptor.adoptFd(fd);
            mScopes.put(mountScope.mountId, mountScope);
            mountScope = null;
            return result;
        }
    } finally {
        IoUtils.closeQuietly(mountScope);
    }
}
 
Example 18
Source Project: android_9.0.0_r45   Source File: FileUtils.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
    final FileDescriptor fd = getInternalFD();
    try {
        int i = 0;
        while (i < data.length) {
            if (sink) {
                i += Os.read(fd, data, i, data.length - i);
            } else {
                i += Os.write(fd, data, i, data.length - i);
            }
        }
    } catch (IOException | ErrnoException e) {
        // Ignored
    } finally {
        if (sink) {
            SystemClock.sleep(TimeUnit.SECONDS.toMillis(1));
        }
        IoUtils.closeQuietly(fd);
    }
}
 
Example 19
Source Project: android_9.0.0_r45   Source File: UiAutomationConnection.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
    try {
        final byte[] buffer = new byte[8192];
        int readByteCount;
        while (true) {
            readByteCount = readFrom.read(buffer);
            if (readByteCount < 0) {
                break;
            }
            writeTo.write(buffer, 0, readByteCount);
            writeTo.flush();
        }
    } catch (IOException ioe) {
        throw new RuntimeException("Error while reading/writing ", ioe);
    } finally {
        IoUtils.closeQuietly(readFrom);
        IoUtils.closeQuietly(writeTo);
    }
}
 
Example 20
Source Project: android_9.0.0_r45   Source File: DocumentsProvider.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Return a list of streamable MIME types matching the filter, which can be passed to
 * {@link #openTypedDocument(String, String, Bundle, CancellationSignal)}.
 *
 * <p>The default implementation returns a MIME type provided by
 * {@link #queryDocument(String, String[])} as long as it matches the filter and the document
 * does not have the {@link Document#FLAG_VIRTUAL_DOCUMENT} flag set.
 *
 * <p>Virtual documents must have at least one streamable format.
 *
 * @see #getStreamTypes(Uri, String)
 * @see #openTypedDocument(String, String, Bundle, CancellationSignal)
 */
public String[] getDocumentStreamTypes(String documentId, String mimeTypeFilter) {
    Cursor cursor = null;
    try {
        cursor = queryDocument(documentId, null);
        if (cursor.moveToFirst()) {
            final String mimeType =
                cursor.getString(cursor.getColumnIndexOrThrow(Document.COLUMN_MIME_TYPE));
            final long flags =
                cursor.getLong(cursor.getColumnIndexOrThrow(Document.COLUMN_FLAGS));
            if ((flags & Document.FLAG_VIRTUAL_DOCUMENT) == 0 && mimeType != null &&
                    mimeTypeMatches(mimeTypeFilter, mimeType)) {
                return new String[] { mimeType };
            }
        }
    } catch (FileNotFoundException e) {
        return null;
    } finally {
        IoUtils.closeQuietly(cursor);
    }

    // No streamable MIME types.
    return null;
}
 
Example 21
Source Project: j2objc   Source File: FileInputStreamTest.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
    try {
        FileOutputStream fos = new FileOutputStream(mOutFd);
        try {
            byte[] buffer = new byte[TOTAL_SIZE];
            for (int i = 0; i < buffer.length; ++i) {
                buffer[i] = (byte) i;
            }
            fos.write(buffer);
        } finally {
            IoUtils.closeQuietly(fos);
            IoUtils.close(mOutFd);
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}
 
Example 22
Source Project: android_9.0.0_r45   Source File: Network.java    License: Apache License 2.0 6 votes vote down vote up
private Socket connectToHost(String host, int port, SocketAddress localAddress)
        throws IOException {
    // Lookup addresses only on this Network.
    InetAddress[] hostAddresses = getAllByName(host);
    // Try all addresses.
    for (int i = 0; i < hostAddresses.length; i++) {
        try {
            Socket socket = createSocket();
            boolean failed = true;
            try {
                if (localAddress != null) socket.bind(localAddress);
                socket.connect(new InetSocketAddress(hostAddresses[i], port));
                failed = false;
                return socket;
            } finally {
                if (failed) IoUtils.closeQuietly(socket);
            }
        } catch (IOException e) {
            if (i == (hostAddresses.length - 1)) throw e;
        }
    }
    throw new UnknownHostException(host);
}
 
Example 23
Source Project: j2objc   Source File: DatagramChannelTest.java    License: Apache License 2.0 6 votes vote down vote up
private void closeBlockedReaderChannel2(ByteBuffer targetBuf)
        throws IOException {
    assertTrue(this.channel2.isBlocking());

    new Thread() {
        public void run() {
            try {
                Thread.sleep(TIME_UNIT);
            } catch (InterruptedException ie) {
                fail();
            }
            IoUtils.closeQuietly(channel2);
        }
    }.start();

    try {
        this.channel2.read(targetBuf);
        fail("Should throw AsynchronousCloseException");
    } catch (AsynchronousCloseException e) {
        // OK.
    }
}
 
Example 24
Source Project: j2objc   Source File: FileInputStream.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void close() throws IOException {
    guard.close();
    synchronized (this) {
        if (channel != null) {
            channel.close();
        }
        if (shouldClose) {
            IoUtils.close(fd);
        } else {
            // An owned fd has been invalidated by IoUtils.close, but
            // we need to explicitly stop using an unowned fd (http://b/4361076).
            fd = new FileDescriptor();
        }
    }
}
 
Example 25
Source Project: AndroidComponentPlugin   Source File: ActivityThread.java    License: Apache License 2.0 5 votes vote down vote up
private void handleDumpService(DumpComponentInfo info) {
    final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
    try {
        Service s = mServices.get(info.token);
        if (s != null) {
            PrintWriter pw = new PrintWriter(new FileOutputStream(info.fd.getFileDescriptor()));
            s.dump(info.fd.getFileDescriptor(), pw, info.args);
            pw.flush();
        }
    } finally {
        IoUtils.closeQuietly(info.fd);
        StrictMode.setThreadPolicy(oldPolicy);
    }
}
 
Example 26
Source Project: AndroidComponentPlugin   Source File: ActivityThread.java    License: Apache License 2.0 5 votes vote down vote up
private void handleDumpActivity(DumpComponentInfo info) {
    final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
    try {
        ActivityClientRecord r = mActivities.get(info.token);
        if (r != null && r.activity != null) {
            PrintWriter pw = new PrintWriter(new FileOutputStream(info.fd.getFileDescriptor()));
            r.activity.dump(info.prefix, info.fd.getFileDescriptor(), pw, info.args);
            pw.flush();
        }
    } finally {
        IoUtils.closeQuietly(info.fd);
        StrictMode.setThreadPolicy(oldPolicy);
    }
}
 
Example 27
Source Project: AndroidComponentPlugin   Source File: ActivityThread.java    License: Apache License 2.0 5 votes vote down vote up
private void handleDumpProvider(DumpComponentInfo info) {
    final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
    try {
        ProviderClientRecord r = mLocalProviders.get(info.token);
        if (r != null && r.mLocalProvider != null) {
            PrintWriter pw = new PrintWriter(new FileOutputStream(info.fd.getFileDescriptor()));
            r.mLocalProvider.dump(info.fd.getFileDescriptor(), pw, info.args);
            pw.flush();
        }
    } finally {
        IoUtils.closeQuietly(info.fd);
        StrictMode.setThreadPolicy(oldPolicy);
    }
}
 
Example 28
Source Project: AndroidComponentPlugin   Source File: DexPathList.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Finds the named native code library on any of the library
 * directories pointed at by this instance. This will find the
 * one in the earliest listed directory, ignoring any that are not
 * readable regular files.
 *
 * @return the complete path to the library or {@code null} if no
 * library was found
 */
public String findLibrary(String libraryName) {
    String fileName = System.mapLibraryName(libraryName);
    for (File directory : nativeLibraryDirectories) {
        String path = new File(directory, fileName).getPath();
        if (IoUtils.canOpenReadOnly(path)) {
            return path;
        }
    }
    return null;
}
 
Example 29
Source Project: AndroidComponentPlugin   Source File: DexPathList.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Finds the named native code library on any of the library
 * directories pointed at by this instance. This will find the
 * one in the earliest listed directory, ignoring any that are not
 * readable regular files.
 *
 * @return the complete path to the library or {@code null} if no
 * library was found
 */
public String findLibrary(String libraryName) {
    String fileName = System.mapLibraryName(libraryName);
    for (File directory : nativeLibraryDirectories) {
        String path = new File(directory, fileName).getPath();
        if (IoUtils.canOpenReadOnly(path)) {
            return path;
        }
    }
    return null;
}
 
Example 30
Source Project: AndroidComponentPlugin   Source File: DexPathList.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Finds the named native code library on any of the library
 * directories pointed at by this instance. This will find the
 * one in the earliest listed directory, ignoring any that are not
 * readable regular files.
 *
 * @return the complete path to the library or {@code null} if no
 * library was found
 */
public String findLibrary(String libraryName) {
    String fileName = System.mapLibraryName(libraryName);
    for (File directory : nativeLibraryDirectories) {
        String path = new File(directory, fileName).getPath();
        if (IoUtils.canOpenReadOnly(path)) {
            return path;
        }
    }
    return null;
}