private boolean checkAlter(Path quellDatei, Path zielDatei) { boolean retValue = false; try { if ((Files.getLastModifiedTime(quellDatei).compareTo(Files.getLastModifiedTime(zielDatei)) > 0)) retValue = true; } catch (IOException e) { e.printStackTrace(); } return retValue; }
/** java 7 中少用file类 基本改成path 通过 file.topath path.tofile来保持兼容 */ @Test public void testPath() { // 创建一个path Path path2 = Paths.get(PATH); System.out.println(path2.toString()); // Path path3 = FileSystems.getDefault().getPath(PATH); System.out.println(path3.toString()); Path path4 = Paths.get(".//MR-FOR-WORK"); System.out.println(path4.toString()); // 得到绝对路径 Path absolutePath = path4.toAbsolutePath(); System.out.println(absolutePath.toString()); // 得到当前运行的路径 String property = System.getProperty("user.dir"); Path path5 = Paths.get(property); System.out.println(property); // 得到真正路径 Path normalize = Paths.get("E:\\360Downloads\\Apk\\tre\\1.txt").normalize(); System.out.println(normalize.toString()); // 获取两个路径之间的距离 Path relativize = normalize.relativize(path2); System.out.println(relativize.toString()); // 获得修改时间 try { FileTime lastModifiedTime = Files.getLastModifiedTime(path2); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
@Override public long getLastModified() { try { return Files.getLastModifiedTime(path).toMillis(); } catch (IOException e) { return -1; } }
@NewEnv(type = NewEnv.Type.NONE) @Test public void testGetLastModifiedTime() throws IOException { Assert.assertEquals(Long.MIN_VALUE, NettyRepository.getLastModifiedTime(null)); Assert.assertEquals(Long.MIN_VALUE, NettyRepository.getLastModifiedTime(Paths.get("Unknown"))); FileTime fileTime = Files.getLastModifiedTime(_repositoryPath); Assert.assertEquals(fileTime.toMillis(), NettyRepository.getLastModifiedTime(_repositoryPath)); }
@Override public boolean isAvailable(SourceId sourceId) { if (sourceId.getStorage() != this) return false; Path file = sourceFileForSource(sourceId); try { return Files.exists(file) && Files.getLastModifiedTime(file).equals(sourceId.myMtime); } catch (IOException ignored) { } return false; }
@Override public SourceId locateModule(ModulePath modulePath) { Path file = sourceFile(baseFile(modulePath)); try { if (Files.exists(file)) { return new SourceId(modulePath, Files.getLastModifiedTime(file)); } } catch (IOException ignored) { } return null; }
public static void main(String[] args) throws IOException { Path path = Paths.get(FileService.FILE_WITH_LINES); System.out.println("Files.isDirectory = " + Files.isDirectory(path)); System.out.println("Files.isExecutable = " + Files.isExecutable(path)); System.out.println("Files.isHidden = " + Files.isHidden(path)); System.out.println("Files.isReadable = " + Files.isReadable(path)); System.out.println("Files.isWritable = " + Files.isWritable(path)); System.out.println("Files.getLastModifiedTime = " + Files.getLastModifiedTime(path)); System.out.println("Files.getOwner = " + Files.getOwner(path)); System.out.println("Files.size = " + Files.size(path)); // change attribute: Files.setAttribute(path, "dos:hidden", false); }
@Override public Abstract.ClassDefinition loadSource(SourceId sourceId, ErrorReporter errorReporter) throws IOException { if (sourceId.getStorage() != this) return null; if (!isAvailable(sourceId)) return null; Path file = sourceFileForSource(sourceId); FileSource fileSource = new FileSource(sourceId, file); Abstract.ClassDefinition definition = fileSource.load(errorReporter); // Make sure we loaded the right revision return Files.getLastModifiedTime(file).equals(sourceId.myMtime) ? definition : null; }
public static void main(String[] args) throws IOException { Path dir = Paths.get(System.getProperty("user.home"), ".sandbox"); Files.createDirectories(dir); Path file = Paths.get(dir.toString(), "timestamp-test.txt"); List<String> lines = new ArrayList<>(); for (int i = 0; i < 10; i++) { lines.add(RandomStringUtils.randomAscii(20)); } Files.write(file, lines); FileTime fileTime = Files.getLastModifiedTime(file); System.out.println(fileTime); System.out.println(LocalDateTime.ofInstant(fileTime.toInstant(), ZoneId.systemDefault())); }
public static boolean isModified(SyncFile syncFile, Path filePath) { if (filePath == null) { return true; } try { FileTime fileTime = Files.getLastModifiedTime(filePath); long modifiedTime = syncFile.getModifiedTime(); if (OSDetector.isUnix()) { modifiedTime = modifiedTime / 1000 * 1000; } if ((fileTime.toMillis() <= modifiedTime) && FileKeyUtil.hasFileKey(filePath, syncFile.getSyncFileId())) { return false; } } catch (IOException ioe) { if (_logger.isDebugEnabled()) { _logger.debug(ioe.getMessage(), ioe); } } try { if ((syncFile.getSize() > 0) && (syncFile.getSize() != Files.size(filePath))) { return true; } } catch (IOException ioe) { if (_logger.isDebugEnabled()) { _logger.debug(ioe.getMessage(), ioe); } } try { String checksum = getChecksum(filePath); return !checksumsEqual(checksum, syncFile.getChecksum()); } catch (IOException ioe) { if (_logger.isDebugEnabled()) { _logger.debug(ioe.getMessage(), ioe); } return true; } }
/** * Indexes the given file using the given writer, or if a directory is given, recurses over files * and directories found under the given directory. * * <p>NOTE: This method indexes one document per input file. This is slow. For good throughput, * put multiple documents into your input file(s). An example of this is in the benchmark module, * which can create "line doc" files, one document per line, using the <a * href="../../../../../contrib-benchmark/org/apache/lucene/benchmark/byTask/tasks/WriteLineDocTask.html" * >WriteLineDocTask</a>. * * @param writer Writer to the index where the given file/dir info will be stored * @param file The file to index, or the directory to recurse into to find files to index * @throws IOException If there is a low-level I/O error */ private void indexDocs(final IndexWriter writer, Path path) throws IOException { if (Files.isDirectory(path)) { Files.walkFileTree( path, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { try { indexDoc(writer, file, attrs.lastModifiedTime().toMillis()); } catch (IOException ignore) { // don't index files that can't be read. } return FileVisitResult.CONTINUE; } }); } else { indexDoc(writer, path, Files.getLastModifiedTime(path).toMillis()); } }
@Test public void testFile() throws Exception { byte[] data = FileServerTestUtil.createRandomData(1024); long lastModified = FileServerTestUtil.getFileSystemTime(System.currentTimeMillis() - Time.DAY); FileResponse fileResponse = new FileResponse(_path, data.length, lastModified, false); NoticeableFuture<FileResponse> noticeableFuture = _asyncBroker.post(_path); _fileResponseChannelHandler.channelRead( _channelHandlerContext, fileResponse, FileServerTestUtil.wrapFirstHalf(data)); ChannelHandler channelHandler = _channelPipeline.first(); Assert.assertTrue(channelHandler instanceof FileUploadChannelHandler); FileUploadChannelHandler fileUploadChannelHandler = (FileUploadChannelHandler) channelHandler; _channelPipeline.fireChannelRead(FileServerTestUtil.wrapSecondHalf(data)); channelHandler = _channelPipeline.first(); Assert.assertFalse(channelHandler instanceof FileUploadChannelHandler); Assert.assertSame(fileResponse, fileUploadChannelHandler.fileResponse); Assert.assertSame(fileResponse, noticeableFuture.get()); Path localFile = fileResponse.getLocalFile(); Assert.assertNotNull(localFile); FileTime fileTime = Files.getLastModifiedTime(localFile); Assert.assertEquals(lastModified, fileTime.toMillis()); Assert.assertArrayEquals(data, Files.readAllBytes(localFile)); Files.delete(localFile); }
/** * Creates Lucene document with the fields: * * <ul> * <li>path: relative path from the constructor * <li>id: the same as path * <li>modified: last modified date of the file * <li>filesize: size of the file * <li>title: name of the file * </ul> * * @return New Lucene document. */ @Override public Document createDocument() { Document doc = new Document(); doc.add(new StringField("path", path.toString(), Field.Store.YES)); doc.add(new StringField("id", path.toString(), Field.Store.YES)); try { doc.add( new StringField( "modified", DateTools.timeToString( Files.getLastModifiedTime(file).toMillis(), DateTools.Resolution.MINUTE), Field.Store.YES)); doc.add(new LongField("filesize", Files.size(file), Field.Store.YES)); } catch (IOException ex) { LOG.error(ex); } doc.add(new TextField("title", file.getFileName().toString(), Field.Store.YES)); return doc; }
public long getLastModifiedTime(Path pathRelativeToProjectRoot) throws IOException { Path path = getPathForRelativePath(pathRelativeToProjectRoot); return Files.getLastModifiedTime(path).toMillis(); }
protected void sendFile( final ChannelHandlerContext channelHandlerContext, FullHttpRequest fullHttpRequest, SyncFile syncFile) throws Exception { Path path = Paths.get(syncFile.getFilePathName()); if (Files.notExists(path)) { _syncTrafficShapingHandler.decrementConnectionsCount(); if (_logger.isTraceEnabled()) { Channel channel = channelHandlerContext.channel(); _logger.trace("Client {}: file not found {}", channel.remoteAddress(), path); } _sendError(channelHandlerContext, NOT_FOUND); return; } if (_logger.isDebugEnabled()) { Channel channel = channelHandlerContext.channel(); _logger.debug("Client {}: sending file {}", channel.remoteAddress(), path); } long modifiedTime = syncFile.getModifiedTime(); long previousModifiedTime = syncFile.getPreviousModifiedTime(); if (OSDetector.isApple()) { modifiedTime = modifiedTime / 1000 * 1000; previousModifiedTime = previousModifiedTime / 1000 * 1000; } FileTime currentFileTime = Files.getLastModifiedTime(path, LinkOption.NOFOLLOW_LINKS); long currentTime = currentFileTime.toMillis(); if ((currentTime != modifiedTime) && (currentTime != previousModifiedTime)) { _syncTrafficShapingHandler.decrementConnectionsCount(); Channel channel = channelHandlerContext.channel(); _logger.error( "Client {}: file modified {}, currentTime {}, modifiedTime " + "{}, previousModifiedTime {}", channel.remoteAddress(), path, currentTime, modifiedTime, previousModifiedTime); _sendError(channelHandlerContext, NOT_FOUND); return; } HttpResponse httpResponse = new DefaultHttpResponse(HTTP_1_1, OK); long size = Files.size(path); HttpUtil.setContentLength(httpResponse, size); HttpHeaders httpHeaders = httpResponse.headers(); MimetypesFileTypeMap mimetypesFileTypeMap = new MimetypesFileTypeMap(); httpHeaders.set( HttpHeaderNames.CONTENT_TYPE, mimetypesFileTypeMap.getContentType(syncFile.getName())); if (HttpUtil.isKeepAlive(fullHttpRequest)) { httpHeaders.set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE); } channelHandlerContext.write(httpResponse); SyncChunkedFile syncChunkedFile = new SyncChunkedFile(path, size, 4 * 1024 * 1024, currentTime); ChannelFuture channelFuture = channelHandlerContext.writeAndFlush( new HttpChunkedInput(syncChunkedFile), channelHandlerContext.newProgressivePromise()); channelFuture.addListener( new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture channelFuture) throws Exception { _syncTrafficShapingHandler.decrementConnectionsCount(); if (channelFuture.isSuccess()) { return; } Throwable exception = channelFuture.cause(); Channel channel = channelHandlerContext.channel(); _logger.error( "Client {}: {}", channel.remoteAddress(), exception.getMessage(), exception); channelHandlerContext.close(); } }); if (!HttpUtil.isKeepAlive(fullHttpRequest)) { channelFuture.addListener(ChannelFutureListener.CLOSE); } }