标签: apache-commons

使用帮助参数时覆盖 required() 参数

我通过以下方式添加解析器选项:

options = new Options()
                .addOption(Option.builder(CONFIG_PARAM)
                        .required()
                        .hasArg(true)
                        .argName(CONFIG_PARAM_NAME + "_path")
                        .desc(CONFIG_PARAM_DESC)
                        .longOpt(CONFIG_PARAM_NAME)
                        .build())
                (...)
                .addOption(Option.builder(HELP_PARAM)
                        .hasArg(false)
                        .longOpt(HELP_PARAM_NAME)
                        .desc(HELP_PARAM_DESC)
                        .build());
Run Code Online (Sandbox Code Playgroud)

现在,我想允许用户仅使用帮助命令,例如。

mypreciousapp --help
Run Code Online (Sandbox Code Playgroud)

使用上述解决方案,这是不可能的 - 我收到有关缺少所需参数的信息

Missing required options: c
Run Code Online (Sandbox Code Playgroud)

有什么方法可以标记帮助参数,以便它可以覆盖所需的参数,并允许单独使用它?我可以手动执行此操作,但首先我想知道 CLI 库中是否有这样的选项。

java command-line-interface apache-commons apache-commons-cli

5
推荐指数
1
解决办法
1120
查看次数

与 apache commons-vfs2 的连接过多

我有一个应用程序需要从 sftp 下载文件。我目前正在使用 apache commons-vfs2

我有一个每 1 分钟运行一次的调度程序。1. 获取远程文件列表(打开连接,获取列表,然后关闭连接) 2. 下载步骤 1 中的文件(打开连接,下载每个文件,然后关闭连接)

如何将连接保持在最低限度?有没有办法限制我与 commons-vfs2 的连接数量?

这是我的代码

private List<FileObject> getRemoteFilesList() throws FileSystemException {
        FileObject[] remoteFiles;
        try {
            manager.init();
            final @Cleanup FileObject remoteDirectoryObject = manager.resolveFile(uri, fileSystemOptions);
            remoteFiles = remoteDirectoryObject.getChildren();

        } finally {
            manager.freeUnusedResources();
            manager.close();
        }
        return Arrays.stream(remoteFiles)
                     .collect(Collectors.toList());
    }

private List<File> downloadRemoteFiles(final List<FileObject> remoteFiles) {
        if(remoteFiles.isEmpty()) {
            return Collections.emptyList();
        }

        final List<File> myCollection = new ArrayList<>();
        try {
            manager.init();

            for (final FileObject myfile : remoteFiles) {
                final File localFile = downloadFile(myfile); …
Run Code Online (Sandbox Code Playgroud)

java apache sftp apache-commons apache-commons-vfs

5
推荐指数
1
解决办法
1920
查看次数

java.io.UnsupportedEncodingException:java.nio.charset.CharsetICU[UTF-8]

安卓工作室3.6

在 build.gradle 中:

compileOptions {
        targetCompatibility JavaVersion.VERSION_1_8
        sourceCompatibility JavaVersion.VERSION_1_8
    }

api 'org.apache.commons:commons-io:1.3.2'
Run Code Online (Sandbox Code Playgroud)

在我的代码中

import org.apache.commons.io.FileUtils
import java.io.*
import java.nio.charset.StandardCharsets

     val file = File(folderPath + File.separator + resultFileName)
                FileUtils.writeStringToFile(
                    file,
                    fileContents,
                    StandardCharsets.UTF_8.toString()
                )
Run Code Online (Sandbox Code Playgroud)

但我收到错误:

 java.nio.charset.CharsetICU[UTF-8]
 java.io.UnsupportedEncodingException: java.nio.charset.CharsetICU[UTF-8]
    at java.nio.charset.Charset.forNameUEE(Charset.java:322)
    at java.lang.String.getBytes(String.java:534)
    at org.apache.commons.io.IOUtils.write(IOUtils.java:810)
    at org.apache.commons.io.FileUtils.writeStringToFile(FileUtils.java:1110)
    at com.myproject.client.common.util.AndroidFileUtil.saveTextToFile(AndroidFileUtil.kt:106)
    at com.myproject.client.service.RecognizedCheckDataService$Companion.saveRecognizedText(RecognizedCheckDataService.kt:117)
    at com.myproject.client.viewmodel.ScanCheckRompetrolViewModel.finishProcessRecognizedCheck(ScanCheckRompetrolViewModel.kt:1059)
    at com.myproject.client.viewmodel.ScanCheckRompetrolViewModel.access$finishProcessRecognizedCheck(ScanCheckRompetrolViewModel.kt:28)
    at com.myproject.client.viewmodel.ScanCheckRompetrolViewModel$runDetector$1.onSuccess(ScanCheckRompetrolViewModel.kt:193)
    at com.myproject.client.viewmodel.ScanCheckRompetrolViewModel$runDetector$1.onSuccess(ScanCheckRompetrolViewModel.kt:28)
    at com.google.android.gms.tasks.zzn.run(Unknown Source)
    at android.os.Handler.handleCallback(Handler.java:739)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:148)
    at android.app.ActivityThread.main(ActivityThread.java:5417)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
 Caused by: java.nio.charset.IllegalCharsetNameException: java.nio.charset.CharsetICU[UTF-8]
Run Code Online (Sandbox Code Playgroud)

android apache-commons

5
推荐指数
1
解决办法
3307
查看次数

如何从 RAM 中完全解析压缩文件?

背景

我需要解析一些各种类型的 zip 文件(出于某种目的获取一些内部文件内容,包括获取它们的名称)。

有些文件无法通过文件路径访问,因为 Android 有 Uri 来访问它们,并且有时 zip 文件位于另一个 zip 文件内。随着使用 SAF 的推动,在某些情况下使用文件路径的可能性甚至更小。

为此,我们有 2 个主要方法来处理:ZipFile类和ZipInputStream类。

问题

当我们有文件路径时,ZipFile 是一个完美的解决方案。在速度方面它也非常有效。

然而,对于其余情况,ZipInputStream 可能会遇到问题,例如这个zip 文件有问题,并导致此异常:

  java.util.zip.ZipException: only DEFLATED entries can have EXT descriptor
        at java.util.zip.ZipInputStream.readLOC(ZipInputStream.java:321)
        at java.util.zip.ZipInputStream.getNextEntry(ZipInputStream.java:124)
Run Code Online (Sandbox Code Playgroud)

我尝试过的

唯一始终有效的解决方案是将文件复制到其他地方,您可以在其中使用 ZipFile 解析它,但这效率很低,并且需要您有可用存储空间,并在完成后删除文件。

因此,我发现 Apache 有一个很好的纯 Java 库(此处)来解析 Zip 文件,并且出于某种原因,它的 InputStream 解决方案(称为“ZipArchiveInputStream”)似乎比本机 ZipInputStream 类更高效。

与我们在本机框架中所拥有的相反,该库提供了更多的灵活性。例如,我可以将整个 zip 文件加载到字节数组中,并让库照常处理它,这甚至适用于我提到的有问题的 Zip 文件:

org.apache.commons.compress.archivers.zip.ZipFile(SeekableInMemoryByteChannel(byteArray)).use { zipFile ->
    for (entry in zipFile.entries) {
      val name = entry.name
      ... // use …
Run Code Online (Sandbox Code Playgroud)

memory java-native-interface zip android apache-commons

5
推荐指数
1
解决办法
836
查看次数

Apache 公共 MultiValuedMap 和 Jackson

我想序列化/反序列化 MultiValuedMap<String,Object>。很难相信 www 中没有示例代码。有谁知道一个例子吗?

这是我的代码片段 import org.apache.commons.collections4.MultiValuedMap;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;

public class MultiValuedMapSerializer extends StdSerializer<MultiValuedMap<String,Object>> {
  private static final long serialVersionUID = 1L;

  public MultiValuedMapSerializer() {
    this(null);
  }

  protected MultiValuedMapSerializer(Class<MultiValuedMap<String,Object>> klass) {
    super(klass);
  }

  @Override
  public void serialize(MultiValuedMap<String,Object> value, JsonGenerator gen, SerializerProvider provider) throws IOException {
    gen.writeStartObject();
    for (Entry<String, Object> entry : value.entries()) {
      if(entry.getValue() instanceOf MultiValuedMap){
        @SuppressWarnings("unchecked")
        MultiValuedMap<String, Object> map = (MultiValuedMap<String, Object>) value;
        if (key != null) {
          gen.writeFieldName(key);
          serialize(map, gen, provider);
        } else { …
Run Code Online (Sandbox Code Playgroud)

java apache-commons jackson fasterxml

5
推荐指数
1
解决办法
1537
查看次数

使用Commons IO复制时锁定文件

我正在使用Apache Commons IO:

     FileUtils.copyFileToDirectory(srcFile, destDir)
Run Code Online (Sandbox Code Playgroud)

如何在复制期间使Windows锁定目标文件?如果我使用Windows,Windows会正确锁定文件:

      Runtime.getRuntime().exec(
      "cmd /c copy /Y \"" + srcFile.getCanonicalPath() + "\" \""
          + destDir.getCanonicalPath() + "\"").waitFor();
Run Code Online (Sandbox Code Playgroud)

注意:争用不是本地程序,而是外部程序.该文件正被复制到远程系统.远程系统在完成复制之前处理文件.由于系统是Windows,因此普通副本会锁定文件并阻止外部程序访问.

java windows file-io apache-commons

4
推荐指数
1
解决办法
4924
查看次数

Apache DefaultHttpClient调用导致"java.lang.RuntimeException:Stub!"

我正在将我的脚趾浸入Android开发中.我有一个项目将与RESTful资源接口,我试图弄清楚如何通过HTTP上的params进行基本GET.从我读过的所有内容来看,共识似乎都支持HTTPClient优于HttpURLConnection.

我编写了一个包装类,其中包含一个方法,该方法负责实例化密钥对象以使用HTTPClient发出请求:

public String get() {  
    String responseString = null;

    HttpClient client = new DefaultHttpClient();
    HttpGet get = new HttpGet();
    try {
        get.setURI(new URI(this.baseURL()));
    } catch (URISyntaxException e1) {
        e1.printStackTrace();
    }

    HttpResponse response;

    try {
        response = client.execute(get);
        responseString = readResponse(response.getEntity());

        if(response != null) {
            System.out.println(responseString);
        }
    } catch(ClientProtocolException e) {
        e.printStackTrace();
    } catch(IOException e) {
        e.printStackTrace();
    }

    return responseString;
Run Code Online (Sandbox Code Playgroud)

}

该行HttpClient client = new DefaultHttpClient();抛出以下异常:

java.lang.RuntimeException: Stub!
at org.apache.http.impl.client.AbstractHttpClient.<init>(AbstractHttpClient.java:5)
at org.apache.http.impl.client.DefaultHttpClient.<init>(DefaultHttpClient.java:7)
at org.rcindustries.appmap.RestClient.get(RestClient.java:54)
at org.rcindustries.appmap.test.functional.RestClientTest.shouldReturnSomeJSon(RestClientTest.java:26)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native …
Run Code Online (Sandbox Code Playgroud)

java android unit-testing httpclient apache-commons

4
推荐指数
2
解决办法
5338
查看次数

使用Signpost和Apache Commons HTTP的OAuth

所以我正在使用Signpost OAuth库for Java.我正在使用Apache Commons HTTP库遇到一些复杂问题.看看下面的代码:

URL url = new URL("http://api.neoseeker.com/forum/get_pm_counts.json");
HttpRequest request = (HttpRequest) url.openConnection();

consumer.sign(request);

request.connect();

System.out.println("Response: " + request.getResponseCode() + " "
        + request.getResponseMessage());
Run Code Online (Sandbox Code Playgroud)

这是从这个例子.您可以看到request曾经是a HttpURLConnection,但因为我将使用Apache Commons HTTP库,我将其更改为HttpRequest对象.现在,我得到错误,当我打电话connect(),getResponseCode()getResponseMessage(),因为这些功能对于一个HttpURLConnection.我HttpRequest将使用哪些函数,以便我可以获得正确编译和运行的代码?谢谢!

java http oauth apache-commons

4
推荐指数
1
解决办法
3746
查看次数

4
推荐指数
1
解决办法
1259
查看次数

使用简单的Apache HttpClient Eclipse项目的NoClassDefFoundError

我正在尝试创建一个简单的Eclipse项目来测试使用HttpClient代码的代码.

我在Eclipse中创建一个简单的Java项目,增加了Junit4测试案例(下面的代码).我加入了httpclient-4.1.3.jar到我手动从Maven的中央下载Eclipse项目在这里,并添加了罐子的Java构建路径.

测试运行时,我收到以下错误:

java.lang.NoClassDefFoundError: org/apache/http/params/HttpParams at HttpClientDemo.test(HttpClientDemo.java:13)

HttpClientDemo很简单:

import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.junit.Test;


public class HttpClientDemo {
   @Test public void test() {
      HttpClient httpclient = new DefaultHttpClient();
   }
}
Run Code Online (Sandbox Code Playgroud)

为什么我收到此错误?

java eclipse httpclient noclassdeffounderror apache-commons

4
推荐指数
1
解决办法
1万
查看次数