小编Shr*_*hri的帖子

为什么 StandardOpenOption.CREATE_NEW 不创建要在 Java 中读取的文件?

这是我的代码:

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)

java file-handling java-nio

3
推荐指数
1
解决办法
503
查看次数

为什么 Collections.binarySearch(List<? extends T> list, T key, Comparator<? super T> c) 方法需要 Comparator 对象作为参数?

这是我的代码:

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

class MyComp implements Comparator<String> {

    @Override
    public int compare(String o1, String o2) {
        return o1.compareTo(o2);
    }
    
}
public class CollectionsAlgo2 {

    public static void main(String[] args) {
        // Create an ArrayList
        ArrayList<String> al = new ArrayList<>();
        
        // Add elements to the array list.
        al.add("C");
        al.add("A");
        al.add("E");
        al.add("B");
        al.add("D");
        al.add("F");
        al.add(1, "A2");
        
        System.out.println("al: "+al);
        Collections.sort(al);
        System.out.println("al after sorting: "+al);
        int pos = Collections.binarySearch(al, "B", new MyComp());
        System.out.println("pos: "+pos);

    }

}
Run Code Online (Sandbox Code Playgroud)

我的问题是在 Collections.binarySearch(List<? extends T> …

java generics collections binary-search comparator

0
推荐指数
1
解决办法
365
查看次数