我需要连接到 4 台机器并从套接字读取数据。我选择使用 nio2 的异步模型。
这是一个伪代码:
class Connector {
private final AsynchronousChannelGroup group;
private final String host;
private final int port
//...
public void connect() {
try (AsynchronousSocketChannel client = AsynchronousSocketChannel.open(group)) {
client.connect(new InetSocketAddress(host(), port())).get(5, TimeUnit.SECONDS);
if (!group.isShutdown()) {
ByteBuffer buffer = ByteBuffer.allocate(1024);
client.read(buffer, 5, TimeUnit.SECONDS, new Attachement(buffer), new ReadHandler(client)); //#1
}
} catch (Exception e) {
//
}
}
private class ReadHandler implements CompletionHandler<Integer, Attachement> {
final AsynchronousSocketChannel channel;
@Override
public void completed(Integer result, Attachement attachment) {
attachment.buffer.clear();
channel.read(attachment.buffer, …Run Code Online (Sandbox Code Playgroud) java.nio.file.FileSystem可以为 zip 文件内的 zip 文件创建a 吗?
如果是这样,URI 是什么样的?
如果没有,我想我将不得不重新使用 ZipInputStream。
我正在尝试递归到下面的方法。当前的实现创建一个 URI“jar:jar:...”。我知道这是错误的(并且可能会让人想起电影角色)。应该是什么?
private static void traverseZip(Path zipFile ) {
// Example: URI uri = URI.create("jar:file:/codeSamples/zipfs/zipfstest.zip");
String sURI = "jar:" + zipFile.toUri().toString();
URI uri = URI.create(sURI);
Map<String, String> env = new HashMap<>();
try (FileSystem fs = FileSystems.newFileSystem(uri, env)) {
Iterable<Path> rootDirs = fs.getRootDirectories();
for (Path rootDir : rootDirs) {
traverseDirectory(rootDir ); // Recurses back into this method for ZIP files
}
} catch (IOException e) {
System.err.println(e);
}
}
Run Code Online (Sandbox Code Playgroud) 这是我的代码:
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SeekableByteChannel;
import java.nio.file.Files;
import java.nio.file.InvalidPathException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
public class ExplicitChannelRead {
public static void main(String[] args) {
int count;
Path filePath = null;
// First, obtain a path to a file.
try {
filePath = Paths.get("test1.txt");
}
catch(InvalidPathException e) {
System.out.println("Path error: "+e);
return;
}
// Next, obtain a channel to that file within a try-with-resources block.
try(SeekableByteChannel fChan =
Files.newByteChannel(filePath, StandardOpenOption.CREATE_NEW)) {
// Allocate a buffer.
ByteBuffer mBuf = …Run Code Online (Sandbox Code Playgroud) 这是我的两个代码片段:
public class Uploader {
private static final String SHA_256 = "SHA-256";
public String getFileSHA2Checksum(InputStream fis) throws IOException {
try {
MessageDigest md5Digest = MessageDigest.getInstance(SHA_256);
return getFileChecksum(md5Digest, fis);
} catch (NoSuchAlgorithmException e) {
return "KO";
}
}
public void transferTo(InputStream fis) throws IOException {
FileUtils.copyInputStreamToFile(fis, file2);
}
Run Code Online (Sandbox Code Playgroud)
我的代码使用此类:
是否有可能copyToFile同时calculateChecksum杠杆InputStream开放?