当前位置: 首页>>代码示例>>Java>>正文


Java NoSuchFileException类代码示例

本文整理汇总了Java中java.nio.file.NoSuchFileException的典型用法代码示例。如果您正苦于以下问题:Java NoSuchFileException类的具体用法?Java NoSuchFileException怎么用?Java NoSuchFileException使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


NoSuchFileException类属于java.nio.file包,在下文中一共展示了NoSuchFileException类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: executeAction

import java.nio.file.NoSuchFileException; //导入依赖的package包/类
@Override
protected void executeAction(DeltaAction action) throws IOException {
    LOG.info("GET "+action.getURL());
    Id dsRef = Id.fromString(action.httpArgs.datasourceName);
    String filenameIRI = determineData(action, dsRef);
    ContentType ct = RDFLanguages.guessContentType(filenameIRI) ;
    String fn = IRILib.IRIToFilename(filenameIRI);
    Path path = Paths.get(fn);
    try ( InputStream in = Files.newInputStream(path) ) {
        action.response.setStatus(HttpSC.OK_200);
        action.response.setContentType(ct.getContentType());
        IOUtils.copy(in, action.response.getOutputStream());
    } catch (NoSuchFileException | FileNotFoundException ex) {
        throw new DeltaNotFoundException(action.getURL());
    }
}
 
开发者ID:afs,项目名称:rdf-delta,代码行数:17,代码来源:S_Data.java

示例2: getInode

import java.nio.file.NoSuchFileException; //导入依赖的package包/类
private long getInode(File file) throws IOException {

        UserDefinedFileAttributeView view = null;
        // windows system and file customer Attribute
        if (OS_WINDOWS.equals(os)) {
            view = Files.getFileAttributeView(file.toPath(), UserDefinedFileAttributeView.class);// 把文件的内容属性值放置在view里面?
            try {
                ByteBuffer buffer = ByteBuffer.allocate(view.size(INODE));// view.size得到inode属性值大小
                view.read(INODE, buffer);// 把属性值放置在buffer中
                buffer.flip();
                return Long.parseLong(Charset.defaultCharset().decode(buffer).toString());// 返回编码后的inode的属性值

            }
            catch (NoSuchFileException e) {
                long winode = random.nextLong();
                view.write(INODE, Charset.defaultCharset().encode(String.valueOf(winode)));
                return winode;
            }
        }
        long inode = (long) Files.getAttribute(file.toPath(), "unix:ino");// 返回unix的inode的属性值
        return inode;
    }
 
开发者ID:uavorg,项目名称:uavstack,代码行数:23,代码来源:ReliableTaildirEventReader.java

示例3: watchDir

import java.nio.file.NoSuchFileException; //导入依赖的package包/类
protected void watchDir(Path dir) throws IOException {
    LOG.debug("Registering watch for {}", dir);
    if (Thread.currentThread().isInterrupted()) {
        LOG.debug("Skipping adding watch since current thread is interrupted.");
    }

    // check if directory is already watched
    // on Windows, check if any parent is already watched
    for (Path path = dir; path != null; path = FILE_TREE_WATCHING_SUPPORTED ? path.getParent() : null) {
        WatchKey previousWatchKey = watchKeys.get(path);
        if (previousWatchKey != null && previousWatchKey.isValid()) {
            LOG.debug("Directory {} is already watched and the watch is valid, not adding another one.", path);
            return;
        }
    }

    int retryCount = 0;
    IOException lastException = null;
    while (retryCount++ < 2) {
        try {
            WatchKey watchKey = dir.register(watchService, WATCH_KINDS, WATCH_MODIFIERS);
            watchKeys.put(dir, watchKey);
            return;
        } catch (IOException e) {
            LOG.debug("Exception in registering for watching of " + dir, e);
            lastException = e;

            if (e instanceof NoSuchFileException) {
                LOG.debug("Return silently since directory doesn't exist.");
                return;
            }

            if (e instanceof FileSystemException && e.getMessage() != null && e.getMessage().contains("Bad file descriptor")) {
                // retry after getting "Bad file descriptor" exception
                LOG.debug("Retrying after 'Bad file descriptor'");
                continue;
            }

            // Windows at least will sometimes throw odd exceptions like java.nio.file.AccessDeniedException
            // if the file gets deleted while the watch is being set up.
            // So, we just ignore the exception if the dir doesn't exist anymore
            if (!Files.exists(dir)) {
                // return silently when directory doesn't exist
                LOG.debug("Return silently since directory doesn't exist.");
                return;
            } else {
                // no retry
                throw e;
            }
        }
    }
    LOG.debug("Retry count exceeded, throwing last exception");
    throw lastException;
}
 
开发者ID:lxxlxx888,项目名称:Reer,代码行数:55,代码来源:WatchServiceRegistrar.java

示例4: prepareErrorList

import java.nio.file.NoSuchFileException; //导入依赖的package包/类
public void prepareErrorList(){
    
    errors.put(new Exception(), Integer.MIN_VALUE);
    errors.put(new NullPointerException(), 10);
    errors.put(new NoSuchFileException("The file could not be found. Sorry for the inconvience"), 20);
    errors.put(new IllegalStateException(), 30);
    errors.put(new FileNotFoundException(), 200);
    errors.put(new AccessDeniedException("The account "+System.getProperty("user.name")+"\nhas not the privileges to do this action."), 40);
    errors.put(new ArrayIndexOutOfBoundsException(),  50);
    errors.put(new UnsupportedOperationException(), 60);
    errors.put(new IOException(), 70);
    errors.put(new MalformedURLException(), 80);
    errors.put(new IllegalArgumentException(), 90);
    
    desc.put(10,"NullPointerException - w którymś momencie w kodzie została napotkana wartość null.");
    desc.put(30,"The value or component has tried to gain illegal state.");
    desc.put(200, "The given file hasn't been found, asure that you gave\nan absolute path and the file exists!");
    desc.put(50, "The index is out of range; it means that the method tried to access the index which is\n"
            + "not in that array.");
    desc.put(60, "Requested operation is not supported at the moment.");
    desc.put(70, "The problem was occured while operating on Input/Output streams.");
    desc.put(90, "The argument given was illegal.");
    desc.put(80, "Given URL is malformed, check\nthat you have write a proper URL address");
}
 
开发者ID:Obsidiam,项目名称:joanne,代码行数:25,代码来源:ErrorLogger.java

示例5: findJsonSpec

import java.nio.file.NoSuchFileException; //导入依赖的package包/类
/**
 * Returns the json files found within the directory provided as argument.
 * Files are looked up in the classpath, or optionally from {@code fileSystem} if its not null.
 */
public static Set<Path> findJsonSpec(FileSystem fileSystem, String optionalPathPrefix, String path) throws IOException {
    Path dir = resolveFile(fileSystem, optionalPathPrefix, path, null);

    if (!Files.isDirectory(dir)) {
        throw new NotDirectoryException(path);
    }

    Set<Path> jsonFiles = new HashSet<>();
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
        for (Path item : stream) {
            if (item.toString().endsWith(JSON_SUFFIX)) {
                jsonFiles.add(item);
            }
        }
    }

    if (jsonFiles.isEmpty()) {
        throw new NoSuchFileException(path, null, "no json files found");
    }

    return jsonFiles;
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:27,代码来源:FileUtils.java

示例6: latestIndexBlobId

import java.nio.file.NoSuchFileException; //导入依赖的package包/类
/**
 * Get the latest snapshot index blob id.  Snapshot index blobs are named index-N, where N is
 * the next version number from when the index blob was written.  Each individual index-N blob is
 * only written once and never overwritten.  The highest numbered index-N blob is the latest one
 * that contains the current snapshots in the repository.
 *
 * Package private for testing
 */
long latestIndexBlobId() throws IOException {
    try {
        // First, try listing all index-N blobs (there should only be two index-N blobs at any given
        // time in a repository if cleanup is happening properly) and pick the index-N blob with the
        // highest N value - this will be the latest index blob for the repository.  Note, we do this
        // instead of directly reading the index.latest blob to get the current index-N blob because
        // index.latest is not written atomically and is not immutable - on every index-N change,
        // we first delete the old index.latest and then write the new one.  If the repository is not
        // read-only, it is possible that we try deleting the index.latest blob while it is being read
        // by some other operation (such as the get snapshots operation).  In some file systems, it is
        // illegal to delete a file while it is being read elsewhere (e.g. Windows).  For read-only
        // repositories, we read for index.latest, both because listing blob prefixes is often unsupported
        // and because the index.latest blob will never be deleted and re-written.
        return listBlobsToGetLatestIndexId();
    } catch (UnsupportedOperationException e) {
        // If its a read-only repository, listing blobs by prefix may not be supported (e.g. a URL repository),
        // in this case, try reading the latest index generation from the index.latest blob
        try {
            return readSnapshotIndexLatestBlob();
        } catch (NoSuchFileException nsfe) {
            return RepositoryData.EMPTY_REPO_GEN;
        }
    }
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:33,代码来源:BlobStoreRepository.java

示例7: upgrade

import java.nio.file.NoSuchFileException; //导入依赖的package包/类
/**
 * Moves the index folder found in <code>source</code> to <code>target</code>
 */
void upgrade(final Index index, final Path source, final Path target) throws IOException {
    boolean success = false;
    try {
        Files.move(source, target, StandardCopyOption.ATOMIC_MOVE);
        success = true;
    } catch (NoSuchFileException | FileNotFoundException exception) {
        // thrown when the source is non-existent because the folder was renamed
        // by another node (shared FS) after we checked if the target exists
        logger.error((Supplier<?>) () -> new ParameterizedMessage("multiple nodes trying to upgrade [{}] in parallel, retry " +
            "upgrading with single node", target), exception);
        throw exception;
    } finally {
        if (success) {
            logger.info("{} moved from [{}] to [{}]", index, source, target);
            logger.trace("{} syncing directory [{}]", index, target);
            IOUtils.fsync(target, true);
        }
    }
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:23,代码来源:IndexFolderUpgrader.java

示例8: testFileSystemExceptions

import java.nio.file.NoSuchFileException; //导入依赖的package包/类
public void testFileSystemExceptions() throws IOException {
    for (FileSystemException ex : Arrays.asList(new FileSystemException("a", "b", "c"),
        new NoSuchFileException("a", "b", "c"),
        new NotDirectoryException("a"),
        new DirectoryNotEmptyException("a"),
        new AtomicMoveNotSupportedException("a", "b", "c"),
        new FileAlreadyExistsException("a", "b", "c"),
        new AccessDeniedException("a", "b", "c"),
        new FileSystemLoopException("a"))) {

        FileSystemException serialize = serialize(ex);
        assertEquals(serialize.getClass(), ex.getClass());
        assertEquals("a", serialize.getFile());
        if (serialize.getClass() == NotDirectoryException.class ||
            serialize.getClass() == FileSystemLoopException.class ||
            serialize.getClass() == DirectoryNotEmptyException.class) {
            assertNull(serialize.getOtherFile());
            assertNull(serialize.getReason());
        } else {
            assertEquals(serialize.getClass().toString(), "b", serialize.getOtherFile());
            assertEquals(serialize.getClass().toString(), "c", serialize.getReason());
        }
    }
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:25,代码来源:ExceptionSerializationTests.java

示例9: readBlob

import java.nio.file.NoSuchFileException; //导入依赖的package包/类
@Override
public InputStream readBlob(String blobName) throws IOException {
    int retry = 0;
    while (retry <= blobStore.numberOfRetries()) {
        try {
            S3Object s3Object = SocketAccess.doPrivileged(() -> blobStore.client().getObject(blobStore.bucket(), buildKey(blobName)));
            return s3Object.getObjectContent();
        } catch (AmazonClientException e) {
            if (blobStore.shouldRetry(e) && (retry < blobStore.numberOfRetries())) {
                retry++;
            } else {
                if (e instanceof AmazonS3Exception) {
                    if (404 == ((AmazonS3Exception) e).getStatusCode()) {
                        throw new NoSuchFileException("Blob object [" + blobName + "] not found: " + e.getMessage());
                    }
                }
                throw e;
            }
        }
    }
    throw new BlobStoreException("retries exhausted while attempting to access blob object [name:" + blobName + ", bucket:" + blobStore.bucket() + "]");
}
 
开发者ID:justor,项目名称:elasticsearch_my,代码行数:23,代码来源:S3BlobContainer.java

示例10: readSession

import java.nio.file.NoSuchFileException; //导入依赖的package包/类
@Override
public SimpleSession readSession(Serializable sessionIdObj) {
    final String sessionId = ensureStringSessionId(sessionIdObj);
    final SimpleSession cachedSession = getFromCache(sessionId);
    if (cachedSession != null) {
        return cachedSession;
    }

    try {
        final SimpleSession session = uncachedRead(sessionId);
        updateCache(sessionId, session);
        return session;
    } catch (FileNotFoundException | NoSuchFileException unused) {
        // Unknown session
        throw new UnknownSessionException(sessionId);
    } catch (ClassNotFoundException | IOException e) {
        throw new SerializationException(e);
    }
}
 
开发者ID:line,项目名称:centraldogma,代码行数:20,代码来源:FileBasedSessionDAO.java

示例11: touch

import java.nio.file.NoSuchFileException; //导入依赖的package包/类
/**
 * Like the unix command of the same name, creates an empty file or updates the last modified
 * timestamp of the existing file at the given path to the current system time.
 */
public static void touch(Path path) throws IOException {
  checkNotNull(path);

  try {
    Files.setLastModifiedTime(path, FileTime.fromMillis(System.currentTimeMillis()));
  } catch (NoSuchFileException e) {
    try {
      Files.createFile(path);
    } catch (FileAlreadyExistsException ignore) {
      // The file didn't exist when we called setLastModifiedTime, but it did when we called
      // createFile, so something else created the file in between. The end result is
      // what we wanted: a new file that probably has its last modified time set to approximately
      // now. Or it could have an arbitrary last modified time set by the creator, but that's no
      // different than if another process set its last modified time to something else after we
      // created it here.
    }
  }
}
 
开发者ID:zugzug90,项目名称:guava-mock,代码行数:23,代码来源:MoreFiles.java

示例12: init

import java.nio.file.NoSuchFileException; //导入依赖的package包/类
@PostConstruct
public void init() throws IOException {
    contractsManager = contractsManagerFactory.getMainContractManager();
    try {
        loadState();
    } catch (FileNotFoundException|NoSuchFileException ignored) {
        state = new BlockState();
        state.blockId = blockId;
        state.created = System.currentTimeMillis();
        storeState();
    }
    //TODO sync state with ethereum
    if (state.partCompleted.timestamp == 0) {
        writer = new FileBlockWriter(blockId, dataFile);
    }
    if (!isProcessingFinished()) {
        cycleTask = executorService.scheduleAtFixedRate(() -> {
            try {
                cycle();
            } catch (Exception e) {
                log.warn("Cycle failed", e);
            }
        }, 1, 1, TimeUnit.SECONDS);
    }
}
 
开发者ID:papyrusglobal,项目名称:state-channels,代码行数:26,代码来源:BlockStateManager.java

示例13: main

import java.nio.file.NoSuchFileException; //导入依赖的package包/类
public static void main(String[] args) throws Throwable {
    try (FileChannel ch = FileChannel.open(BLK_PATH, READ);
         RandomAccessFile file = new RandomAccessFile(BLK_FNAME, "r")) {

        long size1 = ch.size();
        long size2 = file.length();
        if (size1 != size2) {
            throw new RuntimeException("size differs when retrieved" +
                    " in different ways: " + size1 + " != " + size2);
        }
        System.out.println("OK");

    } catch (NoSuchFileException nsfe) {
        System.err.println("File " + BLK_FNAME + " not found." +
                " Skipping test");
    } catch (AccessDeniedException ade) {
        System.err.println("Access to " + BLK_FNAME + " is denied." +
                " Run test as root.");
    }
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:21,代码来源:BlockDeviceSize.java

示例14: scanJar

import java.nio.file.NoSuchFileException; //导入依赖的package包/类
/**
 * Scans a jar file for uses of deprecated APIs.
 *
 * @param jarname the jar file to process
 * @return true on success, false on failure
 */
public boolean scanJar(String jarname) {
    try (JarFile jf = new JarFile(jarname)) {
        out.println(Messages.get("scan.head.jar", jarname));
        finder.addJar(jarname);
        Enumeration<JarEntry> entries = jf.entries();
        while (entries.hasMoreElements()) {
            JarEntry entry = entries.nextElement();
            String name = entry.getName();
            if (name.endsWith(".class")
                    && !name.endsWith("package-info.class")
                    && !name.endsWith("module-info.class")) {
                processClass(ClassFile.read(jf.getInputStream(entry)));
            }
        }
        return true;
    } catch (NoSuchFileException nsfe) {
        errorNoFile(jarname);
    } catch (IOException | ConstantPoolException ex) {
        errorException(ex);
    }
    return false;
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:29,代码来源:Scan.java

示例15: toFilePath

import java.nio.file.NoSuchFileException; //导入依赖的package包/类
/**
 * Returns a file path to a resource in a file tree. If the resource
 * name has a trailing "/" then the file path will locate a directory.
 * Returns {@code null} if the resource does not map to a file in the
 * tree file.
 */
public static Path toFilePath(Path dir, String name) throws IOException {
    boolean expectDirectory = name.endsWith("/");
    if (expectDirectory) {
        name = name.substring(0, name.length() - 1);  // drop trailing "/"
    }
    Path path = toSafeFilePath(dir.getFileSystem(), name);
    if (path != null) {
        Path file = dir.resolve(path);
        try {
            BasicFileAttributes attrs;
            attrs = Files.readAttributes(file, BasicFileAttributes.class);
            if (attrs.isDirectory()
                || (!attrs.isDirectory() && !expectDirectory))
                return file;
        } catch (NoSuchFileException ignore) { }
    }
    return null;
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:25,代码来源:Resources.java


注:本文中的java.nio.file.NoSuchFileException类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。