GVKun编程网logo

Google Hangouts Meet API文档(google docs api)

41

以上就是给各位分享ApacheHttpClient在macOS上因Java11失败,其中也会对theimportorg.apachecannot进行解释,同时本文还将给你拓展Android无法访问or

以上就是给各位分享Apache HttpClient在macOS上因Java 11失败,其中也会对the import org.apache cannot进行解释,同时本文还将给你拓展Android无法访问org.apache.http.client.HttpClient、Apache HttpClient 4和JavaScript、Apache HttpClient POST数据(https)、apache HttpClient 学习系列--2 之HttpContext等相关知识,如果能碰巧解决你现在面临的问题,别忘了关注本站,现在开始吧!

本文目录一览:

Apache HttpClient在macOS上因Java 11失败(the import org.apache cannot)

Apache HttpClient在macOS上因Java 11失败(the import org.apache cannot)

我正在尝试将我的代码从Java 8迁移到Java 11,此代码…

 private static String  readMultiHttpsUrlResultAsString(List<String> mbRecordingIds, String level) throws Exception{    String result = "";    class NaiveTrustStrategy implements TrustStrategy    {        @Override        public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException        {            return true;        }    };    SSLContext sslcontext = org.apache.http.ssl.SSLContexts.custom()            .loadTrustMaterial(new NaiveTrustStrategy())            .build();    CloseableHttpClient httpclient = HttpClients.custom()            .setSSLSocketFactory(new SSLConnectionSocketFactory(sslcontext))            .build();    StringBuilder sb = new StringBuilder("?recording_ids=");    for(String next:mbRecordingIds)    {        sb.append(next + ";");    }    sb.setLength(sb.length() - 1);    try    {        String url = "https://acousticbrainz.org/api/v1"+level+sb;        HttpGet httpget = new HttpGet(url);        try (CloseableHttpResponse response = httpclient.execute(httpget);)        {            int statusCode = response.getStatusLine().getStatusCode();            if(statusCode!=HttpURLConnection.HTTP_OK)            {                return "";            }            HttpEntity entity = response.getEntity();            result = EntityUtils.toString(entity);            EntityUtils.consume(entity);        }    }    finally    {        httpclient.close();    }    return result;}

}

在MacOS上使用(AdoptOpenJdk)Java 11.0.6失败了,

SSLContext sslcontext = org.apache.http.ssl.SSLContexts.custom()            .loadTrustMaterial(new NaiveTrustStrategy())            .build();

它可以在Windows上正常运行(也使用AdoptOpenJdk Java
11.0.6)。一个区别是Windows版本使用从带有jlink的jdk构建的cutdown jre,而MacOS版本使用AdoptOpenJDk
jre构建。MacOS版本是使用InfiniteKinds分支创建的AppBundler

这是堆栈跟踪:

java.lang.NoClassDefFoundError: Could not initialize class sun.security.ssl.SSLContextImpl$TLSContext    at java.base/java.lang.Class.forName0(Native Method)    at java.base/java.lang.Class.forName(Class.java:315)    at java.base/java.security.Provider$Service.getImplClass(Provider.java:1848)    at java.base/java.security.Provider$Service.newInstance(Provider.java:1824)    at java.base/sun.security.jca.GetInstance.getInstance(GetInstance.java:236)    at java.base/sun.security.jca.GetInstance.getInstance(GetInstance.java:164)    at java.base/javax.net.ssl.SSLContext.getInstance(SSLContext.java:168)    at org.apache.http.ssl.SSLContextBuilder.build(SSLContextBuilder.java:269)    at com.jthink.songkong.analyse.acousticbrainz.AcousticBrainz.readMultiHttpsUrlResultAsString(AcousticBrainz.java:409)    at com.jthink.songkong.analyse.acousticbrainz.AcousticBrainz.readLowLevelData(AcousticBrainz.java:373)

我正在使用Apache Httpclient 4.5.3,并且正在使用此lib,因为我是从需要使用ssl的Web服务获取数据的。

更新
我从下面的答案中将示例测试添加到了我的源代码中,并修改了我的构建,以使其在运行应用程序时成为开始类,并为我提供了该堆栈跟踪信息(当从命令行open使用内嵌的Java运行时运行捆绑软件时)由infinitekind
appbundler提供的捆绑包)

Exception in thread "main" java.lang.ExceptionInInitializerError    at java.base/javax.crypto.Cipher.getInstance(Unknown Source)    at java.base/sun.security.ssl.JsseJce.getCipher(Unknown Source)    at java.base/sun.security.ssl.SSLCipher.isTransformationAvailable(Unknown Source)    at java.base/sun.security.ssl.SSLCipher.<init>(Unknown Source)    at java.base/sun.security.ssl.SSLCipher.<clinit>(Unknown Source)    at java.base/sun.security.ssl.CipherSuite.<clinit>(Unknown Source)    at java.base/sun.security.ssl.SSLContextImpl.getApplicableSupportedCipherSuites(Unknown Source)    at java.base/sun.security.ssl.SSLContextImpl$AbstractTLSContext.<clinit>(Unknown Source)    at java.base/java.lang.Class.forName0(Native Method)    at java.base/java.lang.Class.forName(Unknown Source)    at java.base/java.security.Provider$Service.getImplClass(Unknown Source)    at java.base/java.security.Provider$Service.newInstance(Unknown Source)    at java.base/sun.security.jca.GetInstance.getInstance(Unknown Source)    at java.base/sun.security.jca.GetInstance.getInstance(Unknown Source)    at java.base/javax.net.ssl.SSLContext.getInstance(Unknown Source)    at org.apache.http.ssl.SSLContextBuilder.build(SSLContextBuilder.java:389)    at Example.main(Example.java:23)Caused by: java.lang.SecurityException: Can not initialize cryptographic mechanism    at java.base/javax.crypto.JceSecurity.<clinit>(Unknown Source)    ... 17 moreCaused by: java.lang.SecurityException: Can''t read cryptographic policy directory: unlimited    at java.base/javax.crypto.JceSecurity.setupJurisdictionPolicies(Unknown Source)    at java.base/javax.crypto.JceSecurity$1.run(Unknown Source)    at java.base/javax.crypto.JceSecurity$1.run(Unknown Source)    at java.base/java.security.AccessController.doPrivileged(Native Method)    ... 18 more

这与我以前有过不同,但是也许这是根本原因还是这种误导?

而如果我只是运行java -jar songkong6.9.jar它,那么它将运行Example并打印出 Loaded 没有错误,如果我从/
Library / Java指定完整路径,则它在所有情况下都适用(Java 11 / Java 14 / JDk和JRE)

更新 根据以下答案,我已经取得了一些进展。

安装在MacOS上的JRE包含一个conf文件夹,当使用InfiniteKinds
appbundler将JRE添加到我的捆绑包(SongKong)中时,它没有conf文件夹。它确实有一个lib /
security文件夹,其中包含,default.policy但这似乎还不够。

pauls-Mac-mini:Home paul$ ls -lR lib/securitytotal 704-rw-r--r--  1 paul  admin    1253 22 Apr 14:56 blacklisted.certs-rw-r--r--  1 paul  admin  103147 22 Apr 14:56 cacerts-rw-r--r--  1 paul  admin    8979 22 Apr 16:01 default.policy-rw-r--r--  1 paul  admin  233897 22 Apr 14:56 public_suffix_list.dat

安装构建的捆绑包后,如果我手动将conf文件夹从已安装的JRE复制到Java插件的Home文件夹中

例如

/Applications/SongKong.app/Contents/PlugIns/adoptopenjdk-11.jre/Contents/Home

位置,则示例代码和我的原始代码在从bundle中运行时都不会出现错误。

此外,似乎要查找的是无限文件夹及其内容(两个文件实际上是相同的),因此,如果我删除了几个文件,则剩下的就是

pauls-Mac-mini:Home paul$ pwd/Applications/SongKong.app/Contents/PlugIns/adoptopenjdk-11.jre/Contents/Homepauls-Mac-mini:Home paul$ ls -lR conftotal 0drwxr-xr-x  3 paul  admin  96 22 Apr 15:14 securityconf/security:total 0drwxr-xr-x  3 paul  admin  96 22 Apr 15:22 policyconf/security/policy:total 0drwxr-xr-x  4 paul  admin  128 22 Apr 15:28 unlimitedconf/security/policy/unlimited:total 16-rw-r--r--  1 paul  admin  146 22 Apr 15:06 default_US_export.policy-rw-r--r--  1 paul  admin  193 22 Apr 15:06 default_local.policy

然后它继续工作。

问题(除了为什么它不能开箱即用之外)是我认为我无法将文件复制到经过硬化的运行时应用程序的此位置,因此我需要将这些策略文件存储在其他位置,以便可以将其作为appbundler构建的一部分进行安装。因此,作为测试,我已重命名conf文件conf.old夹folder并将以下参数添加到捆绑包中

<string>-Djava.security.policy=/Applications/SongKong.app/Contents/PlugIns/adoptopenjdk-11.jre/Contents/Home/conf.old/security/policy/unlimited/default_local.policy</string>

或替换而不是附加策略文件

<string>-Djava.security.policy==/Applications/SongKong.app/Contents/PlugIns/adoptopenjdk-11.jre/Contents/Home/conf.old/security/policy/unlimited/default_local.policy</string>

但这是行不通的,我尝试了各种值,但没有任何效果。唯一有效的方法是将其保留在conf子文件夹中,然后不管是否传递此参数都无关紧要。(我也尝试添加-Dsecurity.manager作为另一个选项,但这只是导致有关日志记录权限的新错误。)

答案1

小编典典

最终,在Anish的帮助下,解决了缺少策略文件的问题,而这仅仅是使用AppBunder构建的包的问题。

jdk代码似乎真的希望conf在JRE中有一个文件夹,OpenJDk中有一个文件夹,但没有一次与AppBundler捆绑到我的应用程序中。因此,我下载了最新的AppBundler
src代码并对其进行了重建,然后重新构建了我的appbundle,并对其进行了修复,现在包含conf文件夹,并且应用程序运行时没有错误。

Android无法访问org.apache.http.client.HttpClient

Android无法访问org.apache.http.client.HttpClient

我正在使用android studio来创build一个应用程序,使得一个GET请求到服务器。 我的代码是这样的:

import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGetHC4; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; public class HTTPHelper { private String base; public HTTPHelper (String base) { this.base = base; } public String doGet (String path) { try { CloseableHttpClient client = HttpClientBuilder.create().build(); HttpGetHC4 get = new HttpGetHC4(path); CloseableHttpResponse response = client.execute(get); return ""; } catch (Exception e) { return null; } } }

可以肯定的是Android Studio标志着这一行

client.execute(get);

有一个错误:

如何使用PHP在URL中传递URL(作为GET参数)?

.htaccess重写可以仍然使用获取variables的漂亮的URL

在Windows任务计划程序中使用$ _GEtvariables的PHP脚本

Ruby获取方法将我的input截断为256个字符

403发送GET数据时出现禁止的错误

说“不能访问org.apache.http.client.HttpClient”

这是我的gradle文件:

apply plugin: ''com.android.application'' android { compileSdkVersion 23 buildToolsversion "23.0.0" defaultConfig { applicationId "principal.halloween" minSdkVersion 16 targetSdkVersion 23 versionCode 1 versionName "1.0" } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile(''proguard-android.txt''),''proguard-rules.pro'' } } } dependencies { compile filetree(dir: ''libs'',include: [''*.jar'']) compile ''com.android.support:appcompat-v7:23.0.0'' compile ''com.pubnub:pubnub-android:3.7.5'' compile ''com.google.code.gson:gson:2.3.1'' compile group: ''org.apache.httpcomponents'',name: ''httpclient-android'',version: ''4.3.5.1'' compile ''org.apache.httpcomponents:httpclient:4.3.6'' }

Git fetch github:索引包失败

vbs如何从命令行命令得到结果

replace$ _GET,使其从命令行工作

Cleacase如何知道一个目录是一个视图?

使用GET参数时,Apache Redirect 301失败,例如?blah =

在Android SDK 23中

HttpClient被弃用,因为它推断,你可以迁移你的代码在HttpURLConnection

https://developer.android.com/about/versions/marshmallow/android-6.0-changes.html#behavior-apache-http-client

你可以使用这个,但不建议了

android { useLibrary ''org.apache.http.legacy'' }

对于HttpURLConnection

URL url = new URL(urlString); HttpURLConnection connection = (HttpURLConnection)url.openConnection(); connection.setRequestMethod("GET"); connection.setDoInput(true); connection.connect();

这是因为现在sdk 23中不支持HttpClient。 尝试在你的gradle中添加这个。

android { useLibrary ''org.apache.http.legacy'' }

如果这不起作用,只需下载HttpClient jar文件并添加到您的库。

如果仍然无法正常工作,则必须将您的compileSdkVersion降级到22或更低。

总结

以上是小编为你收集整理的Android无法访问org.apache.http.client.HttpClient全部内容。

如果觉得小编网站内容还不错,欢迎将小编网站推荐给好友。

Apache HttpClient 4和JavaScript

Apache HttpClient 4和JavaScript

我使用Apache
HttpClient访问网页。我想单击链接,但是链接是javaScript,我如何处理对javascript链接的点击并遵循url重定向?

示例javascript和html代码:

<a href="javascript:send(32023,'YGHN_JKM','8LMK');"> link</a>


function send(content_id,fic,cgRate) {
        var params = new Hash();
        params.set('content_id',content_id);
        params.set('tool',fic);
        params.set('cgRate',cgRate);

        new Ajax.Updater('return','/mypkg/tools',{
            method: 'post',parameters: params,evalScripts: true,onInitialize: new Effect.Appear('loader',{duration: 0.0}),onComplete: new Effect.Fade('loader',{duration: 1.2})
        });
}

Apache HttpClient POST数据(https)

Apache HttpClient POST数据(https)

测试用的httpclient版本

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.1.2</version>
    <scope>test</scope>
</dependency>

1.传键值对

http://www.androidsnippets.com/executing-a-http-post-request-with-httpclient

2.发送https请求
http://javaskeleton.blogspot.it/2010/07/avoiding-peer-not-authenticated-with.html

最终测试代码:

public class LoginTest {
    @Test
    public void testHttpPost() throws Exception {
        HttpClient client = new DefaultHttpClient();
        client = WebClientDevWrapper.wrapClient(client);

        HttpPost post = new HttpPost("https://localhost:8443/login");
//        StringEntity entity = new StringEntity("user=test@abc.com&pwd=111&type=x");
//        post.setEntity(entity);
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("user", "test@abc.com"));
        nameValuePairs.add(new BasicNameValuePair("pwd", "111"));
        nameValuePairs.add(new BasicNameValuePair("type", "x"));
        post.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        HttpResponse res = client.execute(post);
        System.out.println(res.getStatusLine());

        BufferedReader br = new BufferedReader(new InputStreamReader(res.getEntity().getContent()));
        String line = br.readLine();
        while (line != null) {
            System.out.println(line);
            line = br.readLine();
        }
        client.getConnectionManager().shutdown();
    }
}

工具类:

/*
This code is public domain: you are free to use, link and/or modify it in any way you want, for all purposes including commercial applications. 
*/
public class WebClientDevWrapper {

    public static HttpClient wrapClient(HttpClient base) throws Exception {
        SSLContext ctx = SSLContext.getInstance("TLS");
        X509TrustManager tm = new X509TrustManager() {
            @Override
            public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws java.security.cert.CertificateException {
            }

            @Override
            public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws java.security.cert.CertificateException {
            }

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return new java.security.cert.X509Certificate[0];
            }
        };
        ctx.init(null, new TrustManager[]{tm}, null);
        SSLSocketFactory ssf = new SSLSocketFactory(ctx);
        ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        ClientConnectionManager ccm = base.getConnectionManager();
        SchemeRegistry sr = ccm.getSchemeRegistry();
        sr.register(new Scheme("https", ssf, 443));
        return new DefaultHttpClient(ccm, base.getParams());
    }
}

 使用命令行测试:

curl -k -X POST https://localhost:8443/login --data "user=test@abc.com&pwd=111&type=x"

待研究http://my.oschina.net/wenziqiu/blog/339630,看起来更简单的样子。


apache HttpClient 学习系列--2 之HttpContext

apache HttpClient 学习系列--2 之HttpContext

首先是一个Servlet用于本次试验。

package com.lu.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@SuppressWarnings("serial")
public class RirectServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        this.doPost(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");

        OutputStream out = response.getOutputStream();
        PrintWriter pw = new PrintWriter(out);

        // 记录返回的内容
        String returnContent = null;

        HttpSession session = request.getSession();
        String user = (String) session.getAttribute("username");

        // 如果不为空,说明已登录
        if (user != null) {
            returnContent = "you have been logined, " + user;
        } else {
            // 为空说明未登录,设置username到session中
            String username = request.getParameter("username");
            session.setAttribute("username", username);
            returnContent = "login success";
        }

        try {
            pw.println(returnContent);
        } finally {
            pw.close();
            out.close();
        }
    }

}

在本机中访问URI为:http://localhost:8080/spiderweb/RirectServlet

下面看请求

package com.lu.test;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;

public class HttpClientTest {

    private static HttpContext localContext = new BasicHttpContext();
    private static HttpClientContext context = HttpClientContext
            .adapt(localContext);

    public static void main(String[] args) throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();

        try {
            // 模拟表单
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("username", "**"));
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params,
                    "UTF-8");
            HttpPost httpPost = new HttpPost(
                    "http://localhost:8080/spiderweb/RirectServlet");
            httpPost.setEntity(entity);

            // 将HttpClientContext传入execute()中
            CloseableHttpResponse response = httpClient.execute(httpPost,
                    context);

            try {
                HttpEntity responseEntity = response.getEntity();
                System.out.println(EntityUtils.toString(responseEntity));

            } finally {
                response.close();
            }
        } finally {
            httpClient.close();
        }

        CloseableHttpClient httpClient2 = HttpClients.createDefault();

        try {
            HttpGet httpGet = new HttpGet(
                    "http://localhost:8080/spiderweb/RirectServlet");

            // 设置相同的HttpClientContext
            CloseableHttpResponse response = httpClient2.execute(httpGet,
                    context);
            try {
                HttpEntity entity = response.getEntity();
                System.out.println(EntityUtils.toString(entity));
            } finally {
                response.close();
            }
        } finally {
            httpClient2.close();
        }

    }
}

输出结果为:

login success
you have been logined, **


可能大家认为这个结果很正常。第一次登陆了,第二次肯定会输出you have been logined, **。但是大家别忘了,现在不是在浏览器环境下,浏览器会帮你提取服务器传回的sessionId并在你下次请求的时候传给服务器,那么两次请求用的就是同一个session对象,那么自然的就会有上面的输出。

但是现在是在自己写代码访问。我们没有获取sessionId,也没有向服务器传送sessionId,那么两次请求服务器就会为你创建两个sessionId不同的session对象。

那为什么输出结果却是跟浏览器得到的结果一样呢?肯定是什么东西为我们自动完成了获取sessionId传送sessionId的功能。毫无疑问,就是context。 BasicHttpContext里有个Map<Object,Object>的对象用来记录一次请求响应的信息,当响应信息返回时,就会被set到context里,当然响应的cookie信息也就被存储在context里,包括传回的sessionId。

当第二次请求的时候传入相同的context,那么请求的过程中会将context里的sessionId提取出来传给服务器,sessionId一样,自然而然的就是同一个session对象。
那么大家明白context的作用了吗?
按照官方教程的说法来说

代表一个逻辑相关的会话的多个请求序列应该具有相同的HttpContext实例以确保请求之间的信息状态的自动传播



由于初学,不对的地方还望大家指出。

关于Apache HttpClient在macOS上因Java 11失败the import org.apache cannot的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于Android无法访问org.apache.http.client.HttpClient、Apache HttpClient 4和JavaScript、Apache HttpClient POST数据(https)、apache HttpClient 学习系列--2 之HttpContext等相关知识的信息别忘了在本站进行查找喔。

在这里,我们将给大家分享关于如何使用Apache POI获取PPTX幻灯片注释文本?的知识,同时也会涉及到如何更有效地apache poi pptx 中文乱码 乱码、Apache POI操作pptx基本使用、java – 如何使用Apache POI选择和粗体整个工作表、java-使用apache poi读取.xlsx文件会在Linux机器上产生org.apache.poi.POIXMLException的内容。

本文目录一览:

如何使用Apache POI获取PPTX幻灯片注释文本?

如何使用Apache POI获取PPTX幻灯片注释文本?

到目前为止,我只有一个有效的代码可以从ppt幻灯片笔记中检索文本

try {    FileInputStream is = new FileInputStream("C:\\sample\\test.ppt");    SlideShow ppt = new SlideShow(is);    Slide[] slide = ppt.getSlides();    for (int i = 0; i < slide.length; i++) {        System.out.println(i);        TextRun[] runs = slide[i].getNotesSheet().getTextRuns();        if (runs.length < 1) {            System.out.println("null");        } else {            for (TextRun run : runs) {                System.out.println(" > " + run.getText());            }        }    }} catch (IOException ioe) {}

但是,如何从pptx幻灯片笔记中检索文本?

答案1

小编典典

经过不断的反复试验,找到了解决方案。

try {    FileInputStream fis = new FileInputStream("C:\\sample\\sample.pptx");    XMLSlideShow pptxshow = new XMLSlideShow(fis);    XSLFSlide[] slide2 = pptxshow.getSlides();    for (int i = 0; i < slide2.length; i++) {        System.out.println(i);        try {            XSLFNotes mynotes = slide2[i].getNotes();            for (XSLFShape shape : mynotes) {                if (shape instanceof XSLFTextShape) {                    XSLFTextShape txShape = (XSLFTextShape) shape;                    for (XSLFTextParagraph xslfParagraph : txShape.getTextParagraphs()) {                        System.out.println(xslfParagraph.getText());                    }                }            }        } catch (Exception e) {        }    }} catch (IOException e) {}

apache poi pptx 中文乱码 乱码

apache poi pptx 中文乱码 乱码

各位大牛,

使用 apache poi hslf 转换 ppt 97-03 格式中文编码可以这样: 代码 1.

当使用 xslf 转换 pptx 2007 格式怎么编码呢?直接转中文乱码!

代码 1:

  // ####hslf 支持中文 ####
                TextRun[] truns = slide[i].getTextRuns();
                String title = slide[i].getTitle();
                for (int k = 0; k < truns.length; k++) {
                    RichTextRun[] rtruns = truns[k].getRichTextRuns();
                    for (int l = 0; l < rtruns.length; l++) {
                        int index = rtruns[l].getFontIndex();
                        String name = rtruns[l].getFontName();
                        rtruns[l].setFontIndex(1);
                        rtruns [l].setFontName ("宋体");
                        // System.out.println(rtruns[l].getText());
                    }
                }

Apache POI操作pptx基本使用

Apache POI操作pptx基本使用

最近有一个ppt操作的需求,因此查了下相关的资料

ppt分类

  (1)2007版之前的

    是基于二进制的文件格式

    细节没有完全公开,第三方厂商多是用单向工程方法猜测和分析出来的。WPS做得好一些,但开源的只有做得很差的LibreOffice(原OpenOffice)

  (2)2007版以后的

    是基于OOXML开放文档规范的,本质是一个ZIP包,压缩了XML文档和相关资源。

    OOXML是是一种简洁、可靠的文件格式,这类格式可以更好地实现文档与后端系统之间的数据集成。

java工具

  (1)Apache POI 

    Apache软件基金会的开放源码函式库,POI提供API给Java程序

    (2)Aspose.Slides

    是一款处理pptx的商业软件

  (3)Jacob

    Java-COM Bridge

    在Java与微软的COM组件之间构建一座桥梁。使用Jacob自带的DLL动态链接库,并通过JNI的方式实现了在Java平台上对COM程序的调用。

    MSWordManager 类,是jacob官方发布的工具类,里面有大多数Java操作MS Office的工具。

    在使用Jacob时,很重要的一点是,用户本地系统中必须安装有Word的应用程序。否则也就无法建立Java-COM桥,进而无法解析了。

  因此决定试水 Apache POI 

Apache POI 使用

1.下载http://poi.apache.org/download 

2.修改CLASSPATH

  解压下载的包,将下面5个jar的完整路径添加到CLASSPATH

4.介绍

在POI API中

  PowerPoint PPT——格式为 HSLF     对应poi-scratchpad

  PowerPoint PPTX 格式为 XSLF   对应 poi-ooxml

类型 格式 对应的包 Powerpoint ''97(-2007)PPT HSLF poi-scratchpad-XXX.jar PowerPoint 2007 PPTX XSLF  poi-ooxml-XXX.jar

 

 

 

 

3使用

下面是基于pptx的

(1)生成空白文档

DealDocument.java
import org.apache.poi.xslf.usermodel.XMLSlideShow;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class DealDocument {

    protected String path = "data";
    /**
     * 创建文档
     *
     * @param name
     */
    public void createDocument(String name) {

        XMLSlideShow ppt = new XMLSlideShow();
        String fileName = this.path + File.separator + name;
        File file = new File(fileName);
        try {
            FileOutputStream out = new FileOutputStream(file);
            ppt.write(out);
            System.out.println("Presentation created successfully");
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Main.java

import java.io.*;
import java.net.URL;
import java.util.List;
import org.apache.poi.*;
public class Main {

    public static void main(String[] args) throws IOException{
        System.out.println("Hello World!");
        DealDocument dd = new DealDocument();
        dd.createDocument("example1.pptx");
    }
}

输出

Hello World!
Presentation created successfully

并且在项目根目录的data下生成example1.pptx

说明:

  如果出现错误

 Exception in thread "main" java.lang.IncompatibleClassChangeError: Found class org.apache.poi.util.POILogger, but interface was expected

  这个错误最可能的原因是poi的jar包使用了多个版本

  使用下面的方法可以查看具体使用的哪里的jar包

  (在网上找的,但是版本不同,第三段 org.apache.poi.hslf.HSLFSlideShow.class.getClassLoader()没有找到相关的类,将poi-scratchpad-4.1.0.jar反编译,找了个存在的类,版本是4.1.0)

ClassLoader classloader = org.apache.poi.poifs.filesystem.POIFSFileSystem.class.getClassLoader();
URL res = classloader.getResource("org/apache/poi/poifs/filesystem/POIFSFileSystem.class");
String path = res.getPath();
System.out.println("POI Core came from " + path);

classloader = org.apache.poi.POIDocument.class.getClassLoader();
res = classloader.getResource("org/apache/poi/POIDocument.class");
path = res.getPath();
System.out.println("POI OOXML came from " + path);

classloader=org.apache.poi.hdgf.HDGFDiagram.class.getClassLoader();
res = classloader.getResource("org/apache/poi/hdgf/HDGFDiagram.class");
path = res.getPath();
System.out.println("POI Scratchpad came from " + path);

  输出

POI Core came from file:/C:/Program%20Files/Java/jdk1.8.0_151/jre/lib/ext/poi-3.17.jar!/org/apache/poi/poifs/filesystem/POIFSFileSystem.class
POI OOXML came from file:/C:/Program%20Files/Java/jdk1.8.0_151/jre/lib/ext/poi-3.17.jar!/org/apache/poi/POIDocument.class
POI Scratchpad came from file:/E:/java/project/ppt/ppttest/lib/poi-scratchpad-4.1.0.jar!/org/apache/poi/hdgf/HDGFDiagram.class

  发现确实有一个class走了老包,想起了在对mpp文件进行读写时添加了poi-3.17.jar,因此把相关文件删掉,问题解决

(2)在已有文档添加空白页

在 DealDocument.java 里

在文件 data/tpl1.pptx,追加两个空白页

public void addNewSlide(String name){

        String fileName = this.path + File.separator + name;
        File file = new File(fileName);
        try {
            //opening an existing slide show
            FileInputStream in = new FileInputStream(file);
            XMLSlideShow ppt = new XMLSlideShow(in);
            //adding slides to the slodeshow
            XSLFSlide slide1= ppt.createSlide();
            XSLFSlide slide2 = ppt.createSlide();
            //saving the changes
            FileOutputStream out = new FileOutputStream(file);
            ppt.write(out);
            System.out.println("Presentation edited successfully");
            out.close();
        }catch (IOException e) {
            e.printStackTrace();
        }
}

在mian里的使用

DealDocument dd = new DealDocument();
dd.addNewSlide("tpl1.pptx");

 执行完后,输出

Hello World!
Presentation edited successfully

文件里多了两个空白页

(3)将PPT中幻灯片转成图片

import org.apache.poi.xslf.usermodel.*;
import java.awt.*;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class ImageConvert {

    public void converter(String fileName) {
        BackRS rs = new BackRS();
        File file = new File(fileName);
        String name = file.getName();
        String filePath = file.getParent();
        try {
            FileInputStream in = new FileInputStream(file);
            XMLSlideShow ppt = new XMLSlideShow(in);
            Dimension pgsize = ppt.getPageSize();
            String saveImagePathName = filePath + File.separator + getFileNameNoEx(name)+"_JPG";
            File path = new File(saveImagePathName);
            if (!path.exists()) {
                path.mkdir();
            }
            Integer i = 0;
            BufferedImage img =null;
            for (XSLFSlide slide : ppt.getSlides()) {
                //解决乱码问题
                for(XSLFShape shape : slide.getShapes()){
                    if(shape instanceof XSLFTextShape) {
                        XSLFTextShape tsh = (XSLFTextShape)shape;
                        for(XSLFTextParagraph p : tsh){
                            for(XSLFTextRun r : p){
                                r.setFontFamily("宋体");
                            }
                        }
                    }
                }
                img = new BufferedImage(pgsize.width, pgsize.height, BufferedImage.TYPE_INT_RGB);
                Graphics2D graphics = img.createGraphics();
                graphics.setPaint(Color.white);
                graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));
                slide.draw(graphics);
                FileOutputStream out = new FileOutputStream(path + File.separator + (i+1) + ".JPG");
                i++;
                javax.imageio.ImageIO.write(img, "PNG", out);
                out.close();
            }
            System.out.println("Image successfully converted.");
        } catch (Exception e) {
            System.out.println("error:"+e.getMessage());
        }
    }

    /**
     * 获取文件名,去除扩展名的
     */
    public String getFileNameNoEx(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf(''.'');
            if ((dot > -1) && (dot < (filename.length()))) {
                return filename.substring(0, dot);
            }
        }
        return filename;
    }
}
fileName为完整的路径
图片生成的目录为,和ppt文件同一个目录下,目录名为:ppt文件名+_JPG
图片名为,N.JPG (幻灯片从0开始编号,因此图片名为1.JPG……)

说明:

  虽然对乱码问题做了处理,但是还会出现乱码,而且Apache POI是开源的,创始人离开后版本更新没有推进

  可以改用Aspose.Slide for java  查看

 

java – 如何使用Apache POI选择和粗体整个工作表

java – 如何使用Apache POI选择和粗体整个工作表

我是Apache POI图书馆的初学者.

在VBA中,我知道我可以用下面的代码来选择并粗体整个工作表

Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets(1)
ws.Cells.Font.Bold = True

我可以知道如何通过使用Apache POI库进行编码来选择和粗体整个表格?

谢谢

解决方法

这个 link有一个很好的例子.
Sheet sheet = wb.createSheet("test");
CellStyle cs = wb.createCellStyle();
Font f = wb.createFont();
f.setBoldweight(Font.BOLDWEIGHT_BOLD);
cs.setFont(f);
sheet.setDefaultColumnStyle(1,cs); //set bold for column 1

java-使用apache poi读取.xlsx文件会在Linux机器上产生org.apache.poi.POIXMLException

java-使用apache poi读取.xlsx文件会在Linux机器上产生org.apache.poi.POIXMLException

我有一个读取.xlsx文件并向用户显示内容的应用程序.该应用程序在Windows环境下运行良好.

我将此Web应用程序的.war文件部署在ubuntu服务器上的tomcat6上.我还复制了服务器上的.xlsx文件.

代码中文件的路径正确.

但是线

FileInputStream file = new FileInputStream(new File(FileName));
XSSFWorkbook workbook = new XSSFWorkbook(file);

给出一个错误

java.lang.reflect.InvocationTargetException
org.apache.poi.POIXMLException: java.lang.reflect.InvocationTargetException
org.apache.poi.xssf.usermodel.XSSFFactory.createDocumentPart(XSSFFactory.java:62)
org.apache.poi.POIXMLDocumentPart.read(POIXMLDocumentPart.java:403)
org.apache.poi.POIXMLDocument.load(POIXMLDocument.java:155)
org.apache.poi.xssf.usermodel.XSSFWorkbook.<init>(XSSFWorkbook.java:207)
com.qm.action.GetProjectNames.execute(GetProjectNames.java:107)

我检查了变量FileName是否包含服务器上文件的正确路径和文件名(/usr/local/Metrics/MetricFiles/FY2013_Q2_GIT_Review_Metrics_by_LSS-GC.xlsx)

由于ubunut服务器是VM,因此我已经使用WinSCP复制了.xlsx文件.文件的大小也正确.

为什么在Linux平台上发生此错误?

添加其他异常跟踪

Caused by: java.lang.reflect.InvocationTargetException at 
sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at 
sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57) at 
sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at 
java.lang.reflect.Constructor.newInstance(Constructor.java:525) at 
org.apache.poi.xssf.usermodel.XSSFFactory.createDocumentPart(XSSFFactory.java:60) ... 68 more 
Caused by: java.lang.OutOfMemoryError: Java heap space at java.util.Arrays.copyOfRange(Arrays.java:2694) at java.lang.String.<init>(String.java:203) at 
org.apache.xmlbeans.impl.piccolo.xml.Piccololexer.parseCdataLiteral(Piccololexer.java:3027) at 
org.apache.xmlbeans.impl.piccolo.xml.Piccololexer.parseQuotedTagValue(Piccololexer.java:2936) at 
org.apache.xmlbeans.impl.piccolo.xml.Piccololexer.parseAttributesNS(Piccololexer.java:1754) at 
org.apache.xmlbeans.impl.piccolo.xml.Piccololexer.parSEOpenTagNS(Piccololexer.java:1521) at 
org.apache.xmlbeans.impl.piccolo.xml.Piccololexer.parseTagNS(Piccololexer.java:1362) at 
org.apache.xmlbeans.impl.piccolo.xml.Piccololexer.yylex(Piccololexer.java:4678) at 
org.apache.xmlbeans.impl.piccolo.xml.Piccolo.yylex(Piccolo.java:1290) at 
org.apache.xmlbeans.impl.piccolo.xml.Piccolo.yyparse(Piccolo.java:1400) at 
org.apache.xmlbeans.impl.piccolo.xml.Piccolo.parse(Piccolo.java:714) at 
org.apache.xmlbeans.impl.store.Locale$SaxLoader.load(Locale.java:3439) at 
org.apache.xmlbeans.impl.store.Locale.parsetoXmlObject(Locale.java:1270) at 
org.apache.xmlbeans.impl.store.Locale.parsetoXmlObject(Locale.java:1257) at 
org.apache.xmlbeans.impl.schema.SchemaTypeLoaderBase.parse(SchemaTypeLoaderBase.java:345) at 
org.openxmlformats.schemas.spreadsheetml.x2006.main.StyleSheetDocument$Factory.parse(UnkNown Source) at 
org.apache.poi.xssf.model.StylesTable.readFrom(StylesTable.java:121) at 
org.apache.poi.xssf.model.StylesTable.<init>(StylesTable.java:92) at 
sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at 
sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57) at 
sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at 
java.lang.reflect.Constructor.newInstance(Constructor.java:525) at 
org.apache.poi.xssf.usermodel.XSSFFactory.createDocumentPart(XSSFFactory.java:60) at 
org.apache.poi.POIXMLDocumentPart.read(POIXMLDocumentPart.java:403) at 
org.apache.poi.POIXMLDocument.load(POIXMLDocument.java:155) at 
org.apache.poi.xssf.usermodel.XSSFWorkbook.<init>(XSSFWorkbook.java:207) at 
com.qm.action.GetProjectNames.execute(GetProjectNames.java:107) at 
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at 
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57) at 
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at 
java.lang.reflect.Method.invoke(Method.java:601) at com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:452)

解决方法:

正在对答案发表评论…

您的堆栈跟踪的关键部分是:

Caused by: java.lang.OutOfMemoryError: Java heap space at 
java.util.Arrays.copyOfRange(Arrays.java:2694)

这告诉我们Java没有分配足够的内存来存储处理文件所需的所有数据

如果您需要增加JVM堆大小的帮助,建议您查看this previous question或this one,它们都可以帮助您解决所有问题.

今天关于如何使用Apache POI获取PPTX幻灯片注释文本?的讲解已经结束,谢谢您的阅读,如果想了解更多关于apache poi pptx 中文乱码 乱码、Apache POI操作pptx基本使用、java – 如何使用Apache POI选择和粗体整个工作表、java-使用apache poi读取.xlsx文件会在Linux机器上产生org.apache.poi.POIXMLException的相关知识,请在本站搜索。

在本文中,我们将详细介绍了解UnsupportedOperationException的各个方面,并为您提供关于了解女性健康的相关解答,同时,我们也将为您带来关于Android’InvocationTargetException’和’UnsupportedOperationException’、Arrays.asList给出UnsupportedOperationException、Cause: java.lang.UnsupportedOperationException、Caused by: java.lang.UnsupportedOperationException的有用知识。

本文目录一览:

了解UnsupportedOperationException(了解女性健康)

了解UnsupportedOperationException(了解女性健康)

我不太清楚该在哪里抛出该异常。

例如,我正在实现Future<T>接口,并且不希望任何人调用该方法:

Future#get(long,TimeUnit)。

所以,我可以扔UnsupportedOperationException吗?

public T get(long timeout, TimeUnit unit){    throw new UnsupportedOperationException();}

事情是方法的规范并没有说明抛出异常。反过来,例外

抛出以指示不支持请求的操作。

类UnsupportedOperationException

我的意思是,如果您不希望调用它,通常会抛出它,否则可能会因为不是所有方法都已实现而被认为是不正确的?在我的特定情况下,我认为调用该方法没有道理…

答案1

小编典典

从技术上讲, UnsupportedOperationException
是未经检查的,因此可以抛出任何您喜欢的地方。但是,将其扔在意想不到的地方会使您的班级不太容易使用,因此不建议这样做。

预计将引发 UnsupportedOperationException
的位置在“可选操作”中。Java框架包含许多此类,尤其是在Collections框架中。例如,“
add”是一个可选操作,因为不可变集合不应允许它。如果您不想编写这些方法之一,则应该完全抛出
UnsupportedOperationException

在您的情况下,定时的“
get”对于使用Future是非常重要的,如果不执行,则会引起一些意外。如果要执行此操作,请确保已对其进行了充分的记录,并请注意,这将导致在某些情况下无法使用Future的实现,并可能导致使用它的程序崩溃。

如果您根本没有资源为Future的实现编写定时获取,请考虑使用现有的实现,例如从FutureTask扩展类。

Android’InvocationTargetException’和’UnsupportedOperationException’

Android’InvocationTargetException’和’UnsupportedOperationException’

我在OPPO X905和OPPO X907上遇到了问题,两者都是 Android 4.0.3(API等级15),我没有使用任何更高级别的API,我在Google和SO上搜索过,都与我的问题不同,下面是我的xml文件和崩溃日志,在此先感谢.
xml文件:(分隔符的边距最初是7.5dp,这可能是问题吗?)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/item_full"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#eff0f7"
    android:baselineAligned="false"
    android:orientation="vertical" >
    <RelativeLayout
        android:id="@+id/item_first_half"
        android:layout_width="match_parent"
        android:layout_height="36dp"
        android:orientation="vertical" >
        <View
            android:id="@+id/first_path"
            android:layout_width="4dp"
            android:layout_height="4dp"
            android:layout_marginLeft="40dp"
            android:layout_marginStart="40dp"
            android:background="@drawable/selector_car_action_path" />
        <ImageView
            android:id="@+id/im_car_direction_icon"
            android:layout_width="28dp"
            android:layout_height="28dp"
            android:layout_gravity="top"
            android:layout_marginLeft="28dp"
            android:layout_marginStart="28dp"
            android:layout_marginTop="4dp"
            android:background="@drawable/selector_car_action_background"
            android:padding="2dp"
            android:src="@drawable/selector_navi_icon_63" />
        <View
            android:id="@+id/second_path"
            android:layout_width="4dp"
            android:layout_height="4dp"
            android:layout_below="@id/im_car_direction_icon"
            android:layout_marginLeft="40dp"
            android:layout_marginStart="40dp"
            android:background="@drawable/selector_car_action_path" />
        <TextView
            android:id="@+id/tv_direction"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_marginEnd="15dp"
            android:layout_marginLeft="68dp"
            android:layout_marginRight="15dp"
            android:layout_marginStart="68dp"
            android:singleLine="true"
            android:text=""
            android:textColor="@drawable/selector_car_route_turn_text"
            android:textSize="16sp" />
    </RelativeLayout>
    <RelativeLayout
        android:id="@+id/item_second_half"
        android:layout_width="match_parent"
        android:layout_height="32dp" >
        <View
            android:id="@+id/third_path"
            android:layout_width="4dp"
            android:layout_height="match_parent"
            android:layout_marginLeft="40dp"
            android:layout_marginStart="40dp"
            android:background="@drawable/selector_car_action_path" />
        <TextView
            android:id="@+id/tv_road_name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="68dp"
            android:layout_marginStart="68dp"
            android:layout_marginTop="4dp"
            android:singleLine="true"
            android:text=""
            android:textColor="@drawable/selector_car_route_desc"
            android:textSize="16sp" />
        <TextView
            android:id="@+id/divider_for_road_and_distance"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_marginEnd="7dp"
            android:layout_marginLeft="7dp"
            android:layout_marginRight="7dp"
            android:layout_marginStart="7dp"
            android:layout_marginTop="4dp"
            android:layout_toEndOf="@id/tv_road_name"
            android:layout_toRightOf="@id/tv_road_name"
            android:singleLine="true"
            android:text="|"
            android:textColor="@drawable/selector_car_route_desc"
            android:textSize="16sp" />
        <TextView
            android:id="@+id/tv_ride_distance"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginEnd="15dp"
            android:layout_marginRight="15dp"
            android:layout_marginTop="4dp"
            android:layout_toEndOf="@id/divider_for_road_and_distance"
            android:layout_toRightOf="@id/divider_for_road_and_distance"
            android:singleLine="true"
            android:text=""
            android:textColor="@drawable/selector_car_route_desc"
            android:textSize="16sp" />
        <View
            android:layout_width="match_parent"
            android:layout_height="1px"
            android:layout_alignParentBottom="true"
            android:layout_marginEnd="15dp"
            android:layout_marginLeft="68dp"
            android:layout_marginRight="15dp"
            android:layout_marginStart="68dp"
            android:background="#dee1f0" />
    </RelativeLayout>
</LinearLayout>

drawable / selector_car_route_desc文件是

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_selected="true" android:color="@color/color_999999"/>
    <item android:state_selected="false" android:color="@color/color_333333"/>

</selector>

崩溃日志:

android.view.InflateException: Binary XML file line #106: Error inflating class <unkNown>
android.view.LayoutInflater.createView(LayoutInflater.java:606)
com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56)
android.view.LayoutInflater.onCreateView(LayoutInflater.java:653)
android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:678)
android.view.LayoutInflater.rInflate(LayoutInflater.java:739)
android.view.LayoutInflater.rInflate(LayoutInflater.java:742)
android.view.LayoutInflater.inflate(LayoutInflater.java:489)
android.view.LayoutInflater.inflate(LayoutInflater.java:396)
android.view.LayoutInflater.inflate(LayoutInflater.java:352)
com.tencent.map.ama.route.ui.view.e.<init>(CarRouteShowItem.java:78)
com.tencent.map.ama.route.ui.view.f.a(CarRouteShowView.java:100)
com.tencent.map.ama.route.ui.view.d.a(CarRouteDetailView.java:37)
com.tencent.map.ama.route.ui.MapStateCarRoute.e(MapStateCarRoute.java:418)
com.tencent.map.ama.route.ui.MapStateCarRoute$1.run(MapStateCarRoute.java:255)
android.os.Handler.handleCallback(Handler.java:605)
android.os.Handler.dispatchMessage(Handler.java:92)
android.os.Looper.loop(Looper.java:137)
android.app.ActivityThread.main(ActivityThread.java:4476)
java.lang.reflect.Method.invokeNative(Native Method)
java.lang.reflect.Method.invoke(Method.java:511)
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:808)
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:575)
dalvik.system.NativeStart.main(Native Method)
cause by:
java.lang.reflect.InvocationTargetException: null
java.lang.reflect.Constructor.constructNative(Native Method)
java.lang.reflect.Constructor.newInstance(Constructor.java:417)
android.view.LayoutInflater.createView(LayoutInflater.java:586)
com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56)
android.view.LayoutInflater.onCreateView(LayoutInflater.java:653)
android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:678)
android.view.LayoutInflater.rInflate(LayoutInflater.java:739)
android.view.LayoutInflater.rInflate(LayoutInflater.java:742)
android.view.LayoutInflater.inflate(LayoutInflater.java:489)
android.view.LayoutInflater.inflate(LayoutInflater.java:396)
android.view.LayoutInflater.inflate(LayoutInflater.java:352)
com.tencent.map.ama.route.ui.view.e.<init>(CarRouteShowItem.java:78)
com.tencent.map.ama.route.ui.view.f.a(CarRouteShowView.java:100)
com.tencent.map.ama.route.ui.view.d.a(CarRouteDetailView.java:37)
com.tencent.map.ama.route.ui.MapStateCarRoute.e(MapStateCarRoute.java:418)
com.tencent.map.ama.route.ui.MapStateCarRoute$1.run(MapStateCarRoute.java:255)
android.os.Handler.handleCallback(Handler.java:605)
android.os.Handler.dispatchMessage(Handler.java:92)
android.os.Looper.loop(Looper.java:137)
android.app.ActivityThread.main(ActivityThread.java:4476)
java.lang.reflect.Method.invokeNative(Native Method)
java.lang.reflect.Method.invoke(Method.java:511)
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:808)
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:575)
dalvik.system.NativeStart.main(Native Method)
cause by:
java.lang.UnsupportedOperationException: Can''t convert to dimension: type=0x12
android.content.res.TypedArray.getDimensionPixelSize(TypedArray.java:463)
android.view.View.<init>(View.java:2849)
android.widget.TextView.<init>(TextView.java:499)
android.widget.TextView.<init>(TextView.java:492)
java.lang.reflect.Constructor.constructNative(Native Method)
java.lang.reflect.Constructor.newInstance(Constructor.java:417)
android.view.LayoutInflater.createView(LayoutInflater.java:586)
com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56)
android.view.LayoutInflater.onCreateView(LayoutInflater.java:653)
android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:678)
android.view.LayoutInflater.rInflate(LayoutInflater.java:739)
android.view.LayoutInflater.rInflate(LayoutInflater.java:742)
android.view.LayoutInflater.inflate(LayoutInflater.java:489)
android.view.LayoutInflater.inflate(LayoutInflater.java:396)
android.view.LayoutInflater.inflate(LayoutInflater.java:352)
com.tencent.map.ama.route.ui.view.e.<init>(CarRouteShowItem.java:78)
com.tencent.map.ama.route.ui.view.f.a(CarRouteShowView.java:100)
com.tencent.map.ama.route.ui.view.d.a(CarRouteDetailView.java:37)
com.tencent.map.ama.route.ui.MapStateCarRoute.e(MapStateCarRoute.java:418)
com.tencent.map.ama.route.ui.MapStateCarRoute$1.run(MapStateCarRoute.java:255)
android.os.Handler.handleCallback(Handler.java:605)
android.os.Handler.dispatchMessage(Handler.java:92)
android.os.Looper.loop(Looper.java:137)
android.app.ActivityThread.main(ActivityThread.java:4476)
java.lang.reflect.Method.invokeNative(Native Method)
java.lang.reflect.Method.invoke(Method.java:511)
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:808)
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:575)
dalvik.system.NativeStart.main(Native Method)

CarRouteShowItem.java:78的代码是这样的:

View mView = LayoutInflater.from(mContext).inflate(R.layout.car_route_detail_item,null);

CarRouteShowItem不是View的子代,其代码如下:

public class CarRouteShowItem {

    private Context mContext;

    private View mView;

    public CarRouteShowItem(Context context) {
        mContext = context;

        // mView is used by caller 
        mView = LayoutInflater.from(mContext).inflate(R.layout.car_route_detail_item,null);

        // some view finds 
    }

        // some other methods related with specific logic
}

图形布局可以在Eclipse中从API级别8预览到API级别23,但是当我在API级别15的Android Studio中预览时,它会显示错误消息:无法解析资源@style / Widget.TextView,其他API级别没问题,但我没有使用TextView的样式.

解决方法

你需要的只是一个额外的眼睛:-)

enter image description here

android:layout_height="1px"

希望你现在能看到.第二个RelativeLayout中的最后一个子项,其id为item_second_half,类型为< View,将其更改为

android:layout_height="1dp"

让我尽快回顾一下

Arrays.asList给出UnsupportedOperationException

Arrays.asList给出UnsupportedOperationException

List通过返回Arrays.asList不能通过使用方法如被修改addremove。但是,如果将其传递给该Collections.sort方法,它将可以对数组进行排序而不会出现任何问题(我希望有一个例外)。这似乎是非常不一致的行为。那么ListasList方法返回的对允许的操作是什么?

List<Integer> list = Arrays.asList(5,7, 10 , 8,9);list.remove(2);//ExceptionCollections.sort(list);//Ok, No Exception Sort...System.out.println(list);

我在文档中找不到任何线索。

编辑: 是的,我可以理解为什么它不支持removeadd。但是,它如何支持排序呢?

答案1

小编典典

Arrays.asList返回List由数组支持的固定大小。因此removeadd不支持。set支持。您可以List像对待数组一样看它。数组的长度固定。您不能添加或删除元素,但可以将值分配给数组的索引,这等效于的set方法List。您可以对数组进行排序。

Collections.sort(list)不会更改的大小List,因此可以对固定大小的列表进行排序。排序a所需要做的List就是交换的元素List。为此目的set(index,element)就足够了。

所有这些信息都可以在Javadoc中找到Arrays

/** * Returns a fixed-size list backed by the specified array.  (Changes to * the returned list "write through" to the array.)  This method acts * as bridge between array-based and collection-based APIs, in * combination with {@link Collection#toArray}.  The returned list is * serializable and implements {@link RandomAccess}. * * <p>This method also provides a convenient way to create a fixed-size * list initialized to contain several elements: * <pre> *     List&lt;String&gt; stooges = Arrays.asList("Larry", "Moe", "Curly"); * </pre> * * @param a the array by which the list will be backed * @return a list view of the specified array */ public static <T> List<T> asList(T... a)

如果查看的实现Collections.sort,您会发现它实际上对数组进行了排序。唯一的List方法它要求修改的Listset所述的ListListIterator,它调用Listset(index,element)方法。

public static <T extends Comparable<? super T>> void sort(List<T> list) {  Object[] a = list.toArray();  Arrays.sort(a);  ListIterator<T> i = list.listIterator();  for (int j=0; j<a.length; j++) {      i.next();      i.set((T)a[j]);  }}

Cause: java.lang.UnsupportedOperationException

Cause: java.lang.UnsupportedOperationException

 

运行web项目的时候出现以下错误:

### Cause: java.lang.UnsupportedOperationException
    at org.mybatis.spring.MyBatisExceptionTranslator.translateExceptionIfPossible(MyBatisExceptionTranslator.java:77)
    at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:446)
    at com.sun.proxy.$Proxy74.selectList(Unknown Source)
    at org.mybatis.spring.SqlSessionTemplate.selectList(SqlSessionTemplate.java:230)
    at org.apache.ibatis.binding.MapperMethod.executeForMany(MapperMethod.java:137)
    at org.apache.ibatis.binding.MapperMethod.execute(MapperMethod.java:75)
    at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:59)
    at com.sun.proxy.$Proxy81.getEnjoyCourseByUser(Unknown Source)
    at com.ros.serviceimpl.CourseServiceImpl.getCourseByEngoy(CourseServiceImpl.java:1168)
    at com.ros.controller.CourseController.getCourseByEngoy(CourseController.java:427)
    at com.ros.controller.CourseController$$FastClassBySpringCGLIB$$8a9731c4.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:669)
    at com.ros.controller.CourseController$$EnhancerBySpringCGLIB$$3f51ab5d.getCourseByEngoy(<generated>)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:205)
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:133)
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:97)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827)
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738)
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:967)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:901)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970)
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:661)
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.shiro.web.servlet.ProxiedFilterChain.doFilter(ProxiedFilterChain.java:61)
    at org.apache.shiro.web.servlet.AdviceFilter.executeChain(AdviceFilter.java:108)
    at org.apache.shiro.web.servlet.AdviceFilter.doFilterInternal(AdviceFilter.java:137)
    at org.apache.shiro.web.servlet.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:125)
    at org.apache.shiro.web.servlet.ProxiedFilterChain.doFilter(ProxiedFilterChain.java:66)
    at org.apache.shiro.web.servlet.AbstractShiroFilter.executeChain(AbstractShiroFilter.java:449)
    at org.apache.shiro.web.servlet.AbstractShiroFilter$1.call(AbstractShiroFilter.java:365)
    at org.apache.shiro.subject.support.SubjectCallable.doCall(SubjectCallable.java:90)
    at org.apache.shiro.subject.support.SubjectCallable.call(SubjectCallable.java:83)
    at org.apache.shiro.subject.support.DelegatingSubject.execute(DelegatingSubject.java:387)
    at org.apache.shiro.web.servlet.AbstractShiroFilter.doFilterInternal(AbstractShiroFilter.java:362)
    at org.apache.shiro.web.servlet.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:125)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.HttpPutFormContentFilter.doFilterInternal(HttpPutFormContentFilter.java:108)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:81)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:197)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:478)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:140)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:81)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:87)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:342)
    at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:803)
    at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
    at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1459)
    at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:748)
Caused by: org.apache.ibatis.exceptions.PersistenceException:
### Error querying database.  Cause: java.lang.UnsupportedOperationException
### The error may exist in file [F:\idea\ros1.0\target\classes\mybatis\mapper\CourseMapper.xml]
### The error may involve com.ros.dao.CourseDao.getEnjoyCourseByUser
### The error occurred while handling results
### SQL: SELECT  ros_course.id,  ros_course.c_image AS image,  ros_course.cname,  ros_course.remark,  ros_course.is_favorite AS isFavorite,  ros_course.is_remark AS isRemark,  ros_course.classify,  ros_course.price,  ros_course.visit,  ros_course.update_time AS updateTime FROM  ros_course WHERE  id IN (   SELECT DISTINCT    course_id   FROM    user_course_chartor   WHERE    user_id = ?  ) and  c_type=? LIMIT ?
### Cause: java.lang.UnsupportedOperationException
    at org.apache.ibatis.exceptions.ExceptionFactory.wrapException(ExceptionFactory.java:30)
    at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:150)
    at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:141)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.mybatis.spring.SqlSessionTemplate$SqlSessionInterceptor.invoke(SqlSessionTemplate.java:433)
    ... 80 more
Caused by: java.lang.UnsupportedOperationException
    at org.apache.ibatis.reflection.wrapper.CollectionWrapper.findProperty(CollectionWrapper.java:48)
    at org.apache.ibatis.reflection.MetaObject.findProperty(MetaObject.java:85)
    at org.apache.ibatis.executor.resultset.DefaultResultSetHandler.createAutomaticMappings(DefaultResultSetHandler.java:488)
    at org.apache.ibatis.executor.resultset.DefaultResultSetHandler.applyAutomaticMappings(DefaultResultSetHandler.java:512)
    at org.apache.ibatis.executor.resultset.DefaultResultSetHandler.getRowValue(DefaultResultSetHandler.java:397)
    at org.apache.ibatis.executor.resultset.DefaultResultSetHandler.handleRowValuesForSimpleResultMap(DefaultResultSetHandler.java:351)
    at org.apache.ibatis.executor.resultset.DefaultResultSetHandler.handleRowValues(DefaultResultSetHandler.java:326)
    at org.apache.ibatis.executor.resultset.DefaultResultSetHandler.handleResultSet(DefaultResultSetHandler.java:299)
    at org.apache.ibatis.executor.resultset.DefaultResultSetHandler.handleResultSets(DefaultResultSetHandler.java:192)
    at org.apache.ibatis.executor.statement.PreparedStatementHandler.query(PreparedStatementHandler.java:64)
    at org.apache.ibatis.executor.statement.RoutingStatementHandler.query(RoutingStatementHandler.java:79)
    at org.apache.ibatis.executor.SimpleExecutor.doQuery(SimpleExecutor.java:63)
    at org.apache.ibatis.executor.BaseExecutor.queryFromDatabase(BaseExecutor.java:324)
    at org.apache.ibatis.executor.BaseExecutor.query(BaseExecutor.java:156)
    at org.apache.ibatis.executor.CachingExecutor.query(CachingExecutor.java:109)
    at com.github.pagehelper.PageInterceptor.intercept(PageInterceptor.java:136)
    at org.apache.ibatis.plugin.Plugin.invoke(Plugin.java:61)
    at com.sun.proxy.$Proxy111.query(Unknown Source)
    at org.apache.ibatis.session.defaults.DefaultSqlSession.selectList(DefaultSqlSession.java:148)
    ... 86 more
经过排查可以发现是mybatis中的返回数据错误

在dao的函数定义如下:

在mapper中映射为

调整为:

ok,这个错误解决完成

 

Caused by: java.lang.UnsupportedOperationException

Caused by: java.lang.UnsupportedOperationException

对Arrays.asList()返回的List进行操作之后报错Caused by: java.lang.UnsupportedOperationException

让我们来看一下Arrays.asList的源码:

/** * Returns a {@code List} of the objects in the specified array. The size of the * {@code List} cannot be modified, i.e. adding and removing are unsupported, but * the elements can be set. Setting an element modifies the underlying * array. * * @param array * the array. * @return a {@code List} of the elements of the specified array. */
    @SafeVarargs
    public static <T> List<T> asList(T... array) {
        return new ArrayList<T>(array);
    }

private static class ArrayList<E> extends AbstractList<E> implements
            List<E>, Serializable, RandomAccess {

        private static final long serialVersionUID = -2764017481108945198L;

        private final E[] a;

        ArrayList(E[] storage) {
            if (storage == null) {
                throw new NullPointerException("storage == null");
            }
            a = storage;
        }

        @Override
        public boolean contains(Object object) {
            if (object != null) {
                for (E element : a) {
                    if (object.equals(element)) {
                        return true;
                    }
                }
            } else {
                for (E element : a) {
                    if (element == null) {
                        return true;
                    }
                }
            }
            return false;
        }

        @Override
        public E get(int location) {
            try {
                return a[location];
            } catch (ArrayIndexOutOfBoundsException e) {
                throw java.util.ArrayList.throwIndexOutOfBoundsException(location, a.length);
            }
        }

        @Override
        public int indexOf(Object object) {
            if (object != null) {
                for (int i = 0; i < a.length; i++) {
                    if (object.equals(a[i])) {
                        return i;
                    }
                }
            } else {
                for (int i = 0; i < a.length; i++) {
                    if (a[i] == null) {
                        return i;
                    }
                }
            }
            return -1;
        }

        @Override
        public int lastIndexOf(Object object) {
            if (object != null) {
                for (int i = a.length - 1; i >= 0; i--) {
                    if (object.equals(a[i])) {
                        return i;
                    }
                }
            } else {
                for (int i = a.length - 1; i >= 0; i--) {
                    if (a[i] == null) {
                        return i;
                    }
                }
            }
            return -1;
        }

        @Override
        public E set(int location, E object) {
            E result = a[location];
            a[location] = object;
            return result;
        }

        @Override
        public int size() {
            return a.length;
        }

        @Override
        public Object[] toArray() {
            return a.clone();
        }

        @Override
        @SuppressWarnings({"unchecked", "SuspiciousSystemArraycopy"})
        public <T> T[] toArray(T[] contents) {
            int size = size();
            if (size > contents.length) {
                Class<?> ct = contents.getClass().getComponentType();
                contents = (T[]) Array.newInstance(ct, size);
            }
            System.arraycopy(a, 0, contents, 0, size);
            if (size < contents.length) {
                contents[size] = null;
            }
            return contents;
        }
    }

索噶,原来返回的是Arrays类的静态内部类!这样能会报错也就正常咯。

关于了解UnsupportedOperationException了解女性健康的问题我们已经讲解完毕,感谢您的阅读,如果还想了解更多关于Android’InvocationTargetException’和’UnsupportedOperationException’、Arrays.asList给出UnsupportedOperationException、Cause: java.lang.UnsupportedOperationException、Caused by: java.lang.UnsupportedOperationException等相关内容,可以在本站寻找。

本文的目的是介绍哪个是用Java读取大型excel文件的最佳API?的详细情况,特别关注java读取大量excel的相关信息。我们将通过专业的研究、有关数据的分析等多种方式,为您呈现一个全面的了解哪个是用Java读取大型excel文件的最佳API?的机会,同时也不会遗漏关于c# – 解析大型Excel文件列表失败、java – 在groovy中读取Excel文件的最简单方法?、Java利用jxl.jar操作Excel文件的方法——把两列相同的数据扫描输出到新的Excel文件中、java处理Excel文件---excel文件的创建,删除,写入,读取的知识。

本文目录一览:

哪个是用Java读取大型excel文件的最佳API?(java读取大量excel)

哪个是用Java读取大型excel文件的最佳API?(java读取大量excel)

我的应用程序需要什么

1)读取.xls或.xlsx格式的大型excel文件

2)将每一列插入数据库中的一行,上一列作为下一列的父级

意味着如果我有5列和30,000行,那么我想插入1列作为父级,
第二列是第一列的子级,第三列是第二列的子级,依此类推…即树形结构

现在任何人都可以建议我最好的API以Java语言完成此操作。

经过一番谷歌搜索后,我发现现在有很多API,但这是最好的

参考见

答案1

小编典典

尝试POI,我不确定他们是否读取.xlsx,也许他们使用的是最新版本。

c# – 解析大型Excel文件列表失败

c# – 解析大型Excel文件列表失败

这是一个C#/ VSTO程序.我一直在研究数据捕获项目.范围基本上是“由各种第三方公司发送的过程Excel文件”.实际上,这意味着:

>通过搜索方法找到包含我想要的数据的列.
>从工作簿中获取数据
>清理数据,运行一些计算等
>将清理后的数据输出到新工作簿中

我编写的程序非常适合中小型数据集,约25个工作簿,总共有大约1000行的相关数据.我正在从这些工作簿中获取7列数据.我有一个边缘案例,偶尔我需要运行一个更大的数据集,~50个工作簿,总共有大约8,000行的相关数据(可能还有另外〜2000个重复数据,我也必须删除).

我目前正在通过Parallel.ForEach循环放置文件列表,其中我打开一个新的Excel.Application()来处理具有多个ActiveSheets的每个文件.并行进程在较小的数据集上运行得比按顺序遍历每个数据集要快得多.但是在更大的数据集上,我似乎碰壁了.

我开始收到消息:Microsoft Excel正在等待另一个应用程序完成OLE操作,最终它失败了.切换回顺序foreach确实允许程序完成,但它只是研磨 – 从并行中型数据集的1-3分钟到顺序大型数据集的20分钟.如果我将ParallelOptions.MaxDegreeOfParallelism设置为10,它将完成循环,但仍需要15分钟.如果我将其设置为15,则会失败.如果我不需要,我也真的不喜欢弄乱TPL设置.我也试过插入一个Thread.Sleep来手动减慢速度,但这只会让故障进一步发生.

我关闭工作簿,退出应用程序,然后将ReleaseComObject关闭到Excel对象,并在每个循环结束时使用GC.Collect和GC.WaitForPendingFinalizers.

我现在的想法是:

>将列表分成两半并单独运行
>并行打开一些新的Excel.Application(),但是在该Excel实例内部顺序运行一个文件列表(所以有点像#1,但是使用不同的路径)
>按文件大小分隔列表,并独立/顺序运行一小组非常大的文件,运行其余文件,因为我一直在

我希望得到一些帮助的事情:

>关于真正确保我的记忆被清除的建议(也许Process.Id在所有的开始和结束时都被扭曲了?)
>关于订购并行流程的建议 – 我想知道我是否可以先抛出’大’人,这将使更长时间的流程更加稳定.

我一直在寻找:http://reedcopsey.com/2010/01/26/parallelism-in-net-part-5-partitioning-of-work/,他说“有了你的工作的先验知识,有可能比默认的分区器更有意义地划分数据.”但我真的很难知道分区是否有意义.

真的很感激任何见解!

UPDATE

因此,作为一般规则,我对Excel 2010进行了测试,因为我们在此处使用了2010和2013.我在2013年运行它并且它工作正常 – 运行时间大约4分钟,这是我所期望的.在我放弃2010兼容性之前,还有其他想法吗? 2010机器是64位计算机,64位Office,2013计算机是64位计算机,32位Office.这有关系吗?

解决方法

几年前,我使用excel文件和自动化.然后我遇到了在任务管理器中拥有僵尸进程的问题.虽然我们的计划已经结束,但我认为我退出了正常,但这些流程并没有放弃.

解决方案不是我喜欢的东西,但它是有效的.我可以总结这样的解决方案.

1)永远不要连续使用两个点:

workBook.ActiveSheet.PageSetup

而是使用变量..当你完成重新传递并将它们归零时.

示例:而不是这样做:

m_currentWorkBook.ActiveSheet.PageSetup.LeftFooter = str.ToString();

遵循此功能中的做法. (此功能为excel页脚添加条形码.)

private bool SetBarcode(string text)
    {
            Excel._Worksheet sheet;
            sheet = (Excel._Worksheet)m_currentWorkbook.ActiveSheet;
            try
            {
                StringBuilder str = new StringBuilder();
                str.Append(@"&""IDAutomationHC39M,Regular""&22(");
                str.Append(text);
                str.Append(")");

                Excel.PageSetup setup;
                setup = sheet.PageSetup;
                try
                {
                    setup.LeftFooter = str.ToString();
                }
                finally
                {
                    RemoveReference(setup);
                    setup = null;
                }
            }
            finally
            {
                RemoveReference(sheet);
                sheet = null;
            }

            return true;

    }

这是RemoveReference函数(在此函数中放置null不起作用)

private void RemoveReference(object o)
    {
        try
        {
            System.Runtime.InteropServices.Marshal.ReleaseComObject(o);
        }
        catch
        { }
        finally
        {
            o = null;
        }
    }

如果您遵循这种模式,它保证没有泄漏,没有僵尸进程等.

2)为了创建excel文件你可以使用excel应用程序,但是为了从excel获取数据,我建议使用OleDB.您可以像数据库一样使用excel,并使用SQL查询,数据表等从中获取数据.

示例代码:(而不是填充数据集,您可以使用datareader获取内存性能)

private List<DataTable> getMovieTables()
    {
        List<DataTable> movieTables = new List<DataTable>();
        var connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + excelFilePath + ";Extended Properties=\"Excel 12.0;IMEX=1;HDR=NO;TypeGuessRows=0;ImportMixedTypes=Text\""; ;
        using (var conn = new OleDbConnection(connectionString))
        {
            conn.open();

            DaTarowCollection sheets = conn.GetoleDbSchemaTable(OleDbSchemaGuid.Tables,new object[] { null,null,"TABLE" }).Rows;

            foreach (DaTarow sheet in sheets)
            {

                using (var cmd = conn.CreateCommand())
                {
                    cmd.CommandText = "SELECT * FROM [" + sheet["TABLE_NAME"].ToString() + "] ";

                    var adapter = new OleDbDataAdapter(cmd);
                    var ds = new DataSet();
                    try
                    {
                        adapter.Fill(ds);
                        movieTables.Add(ds.Tables[0]);
                    }
                    catch (Exception ex)
                    {
                        //Debug.WriteLine(ex.ToString());
                        continue;
                    }
                }
            }
        }
        return movieTables;
    }

java – 在groovy中读取Excel文件的最简单方法?

java – 在groovy中读取Excel文件的最简单方法?

是否有任何warappers / utils可用于在Groovy中读取Excel文件.我正在寻找类似于Groovy sql的行函数的东西,如下面的spock测试示例所示.我的目的是将其用于 data driven testing using excel in Spock test framework
import groovy.sql.sql

import spock.lang.*

class DatabaseDriven extends Specification {
  @Shared sql = sql.newInstance("jdbc:h2:mem:","org.h2.Driver")

  // normally an external database would be used,// and the test data wouldn't have to be inserted here
  def setupSpec() {
    sql.execute("create table maxdata (id int primary key,a int,b int,c int)")
    sql.execute("insert into maxdata values (1,3,7,7),(2,5,4,5),(3,9,9)")
  }

  def "maximum of two numbers"() {
    expect:
    Math.max(a,b) == c

    where:
    [a,b,c] << sql.rows("select a,c from maxdata")
  }
}

解决方法

我的一位GUG成员创建了一个使用Apache POI与Excel一起工作的工具,其方式与您描述的方式非常相似.它尚未正式进入图书馆(AFAIK),但可以在他的博客上找到.

它允许您编写如下代码:

new ExcelBuilder("customers.xls").eachLine([labels:true]) {
  new Person(name:"$firstname $lastname",address:address,telephone:phone).save()
}

在这里查看:http://www.technipelago.se/content/technipelago/blog/44

Java利用jxl.jar操作Excel文件的方法——把两列相同的数据扫描输出到新的Excel文件中

Java利用jxl.jar操作Excel文件的方法——把两列相同的数据扫描输出到新的Excel文件中

最近公司在做数据库方面的改造,其中有两个核心库,可以把它们分别命名成A侧库和B侧库,改造的目的是把AB的库整合成一个库,其中表名相同的表要进一步处理,但是每个库中都有上千张表,如果单凭自己逐一查看(即使利用工具)是相当费力的。突然想到以前玩过JXL,所以可以用它写不到百行的代码搞定这个事情。本文共分两部分,第一部分主要介绍JAVA利用JXL操作Excel进行读写操作的方法,如果有JXL使用经验的可以略过;第二部分对第一部分所说的功能进行整合,其核心无非是对文件的读写,只不过这种文件格式比较特殊罢了。

第一部分 JAVA利用JXL操作Excel的基本方法

准备工作:下载jxl.jar并加入到build path中;一个包括两列数据的excel文件放到项目的根目录即可。

无论是.txt还是.xls,其实说白了还是文件,对其进行处理无非就是文件的读写操作,没什么可说的。详见代码:

读取excel:


   
   
import java.io.File; import jxl.Cell; import jxl.Sheet; import jxl.Workbook; public class ReadFromExcel { public static void main(String args[]) { try { Workbook book = Workbook.getWorkbook( new File( " read.xls " )); // 获得第1个工作表对象 Sheet sheet = book.getSheet( 0 ); // 得到第1列第1行的单元格 Cell cell1 = sheet.getCell( 0 , 0 ); // 得到第2列第1行的单元格 Cell cell2 = sheet.getCell( 1 , 0 ); int rows = sheet.getRows(); int counter = 0 ; for ( int i = 0 ; i < rows; i ++ ) { cell1 = sheet.getCell( 0 , i); for ( int j = 0 ; j < rows; j ++ ) { cell2 = sheet.getCell( 1 , j); if (cell1.getContents().equals(cell2.getContents())) { System.out.println(cell2.getContents()); counter ++ ; } } } System.out.println( " counter= " + counter); book.close(); } catch (Exception e) { System.out.println(e); } } }

写入excle:


   
   
import java.io.File; import jxl.Workbook; import jxl.write.Label; import jxl.write.WritableSheet; import jxl.write.WritableWorkbook; public class WriteToExcel { public static void main(String args[]) { try { WritableWorkbook wbook = Workbook.createWorkbook( new File( " write.xls " )); WritableSheet wsheet = wbook.createSheet( " 第一页 " , 0 ); // 在第1行第1列添加“00” wsheet.addCell( new Label( 0 , 0 , " 00 " )); // 在第1行第2列添加“10” wsheet.addCell( new Label( 1 , 0 , " 10 " )); wbook.write(); wbook.close(); } catch (Exception e) { System.out.println(e); } } }

第二部分 把两列中相等的数据扫描出来并输出到控制台并写到新的excel中

其实就是简单的两层循环,由于时间仓促,可优化的地方仍然很大,时间复杂度可以从n2到nlogn,有兴趣的同学可以研究下merge算法!详见代码:


   
   
import java.io.File; import jxl.Cell; import jxl.Sheet; import jxl.Workbook; import jxl.write.Label; import jxl.write.WritableSheet; import jxl.write.WritableWorkbook; public class EqualMerge { public static void main(String args[]) { try { WritableWorkbook toBook = Workbook.createWorkbook( new File( " result.xls " )); WritableSheet toSheet = toBook.createSheet( " 第一页 " , 0 ); Workbook fromBook = Workbook.getWorkbook( new File( " test.xls " )); Sheet sheet = fromBook.getSheet( 0 ); Cell cell1; Cell cell2; int rows = sheet.getRows(); int counter = 0 ; for ( int i = 0 ; i < rows; i ++ ) { cell1 = sheet.getCell( 0 , i); for ( int j = 0 ; j < rows; j ++ ) { cell2 = sheet.getCell( 1 , j); if (cell1.getContents().equals(cell2.getContents())) { System.out.println(cell2.getContents()); toSheet.addCell( new Label( 0 , counter, cell2 .getContents())); counter ++ ; } } } toBook.write(); fromBook.close(); toBook.close(); } catch (Exception e) { System.out.println(e); } } }

总结一下:这个只是个原型,如果想要需要更复杂的功能这种架构并不是合理的,但是应付简单的操作足够了,还有就是excel有两个相关的函数也可实现类似的功能:IF和EXACT。

java处理Excel文件---excel文件的创建,删除,写入,读取

java处理Excel文件---excel文件的创建,删除,写入,读取

下面是小编 jb51.cc 通过网络收集整理的代码片段。

小编小编现在分享给大家,也给大家做个参考。

    package module.system.common;  
      
    import java.io.File;  
    import java.io.FileInputStream;  
    import java.io.FileNotFoundException;  
    import java.io.FileOutputStream;  
    import java.io.IOException;  
    import java.lang.reflect.Field;  
    import java.lang.reflect.Method;  
    import java.util.ArrayList;  
    import java.util.List;  
      
    import org.apache.poi.hssf.usermodel.hssfRow;  
    import org.apache.poi.hssf.usermodel.hssfSheet;  
    import org.apache.poi.hssf.usermodel.hssfWorkbook;  
    import org.apache.poi.poifs.filesystem.POIFSFileSystem;  
    import org.apache.poi.ss.usermodel.Cell;  
    import org.apache.poi.ss.usermodel.Row;  
    import org.apache.poi.ss.usermodel.Sheet;  
      
    /** 
     * 从excel读取数据/往excel中写入 excel有表头,表头每列的内容对应实体类的属性 
     *  
     * @author nagsh 
     *  
     */  
    public class ExcelManage {  
        private hssfWorkbook workbook = null;  
          
        /** 
         * 判断文件是否存在. 
         * @param fileDir  文件路径 
         * @return 
         */  
        public boolean fileExist(String fileDir){  
             boolean flag = false;  
             File file = new File(fileDir);  
             flag = file.exists();  
             return flag;  
        }  
        /** 
         * 判断文件的sheet是否存在. 
         * @param fileDir   文件路径 
         * @param sheetName  表格索引名 
         * @return 
         */  
        public boolean sheetExist(String fileDir,String sheetName){  
             boolean flag = false;  
             File file = new File(fileDir);  
             if(file.exists()){    //文件存在  
                //创建workbook  
                 try {  
                    workbook = new hssfWorkbook(new FileInputStream(file));  
                    //添加Worksheet(不添加sheet时生成的xls文件打开时会报错)  
                    hssfSheet sheet = workbook.getSheet(sheetName);    
                    if(sheet!=null)  
                        flag = true;  
                } catch (Exception e) {  
                    e.printstacktrace();  
                }   
                  
             }else{    //文件不存在  
                 flag = false;  
             }  
               
             return flag;  
        }  
        /** 
         * 创建新excel. 
         * @param fileDir  excel的路径 
         * @param sheetName 要创建的表格索引 
         * @param titleRow excel的第一行即表格头 
         */  
        public void createExcel(String fileDir,String sheetName,String titleRow[]){  
            //创建workbook  
            workbook = new hssfWorkbook();  
            //添加Worksheet(不添加sheet时生成的xls文件打开时会报错)  
            Sheet sheet1 = workbook.createSheet(sheetName);    
            //新建文件  
            FileOutputStream out = null;  
            try {  
                //添加表头  
                Row row = workbook.getSheet(sheetName).createRow(0);    //创建第一行    
                for(int i = 0;i < titleRow.length;i++){  
                    Cell cell = row.createCell(i);  
                    cell.setCellValue(titleRow[i]);  
                }  
                  
                out = new FileOutputStream(fileDir);  
                workbook.write(out);  
            } catch (Exception e) {  
                e.printstacktrace();  
            } finally {    
                try {    
                    out.close();    
                } catch (IOException e) {    
                    e.printstacktrace();  
                }    
            }    
          
      
        }  
        /** 
         * 删除文件. 
         * @param fileDir  文件路径 
         */  
        public boolean deleteExcel(String fileDir){  
            boolean flag = false;  
            File file = new File(fileDir);  
            // 判断目录或文件是否存在    
            if (!file.exists()) {  // 不存在返回 false    
                return flag;    
            } else {    
                // 判断是否为文件    
                if (file.isFile()) {  // 为文件时调用删除文件方法    
                    file.delete();  
                    flag = true;  
                }   
            }  
            return flag;  
        }  
        /** 
         * 往excel中写入(已存在的数据无法写入). 
         * @param fileDir    文件路径 
         * @param sheetName  表格索引 
         * @param object 
         */  
        public void writetoExcel(String fileDir,Object object){  
            //创建workbook  
            File file = new File(fileDir);  
            try {  
                workbook = new hssfWorkbook(new FileInputStream(file));  
            } catch (FileNotFoundException e) {  
                e.printstacktrace();  
            } catch (IOException e) {  
                e.printstacktrace();  
            }  
            //流  
            FileOutputStream out = null;  
            hssfSheet sheet = workbook.getSheet(sheetName);  
            // 获取表格的总行数  
            int rowCount = sheet.getLastRowNum() + 1; // 需要加一  
            // 获取表头的列数  
            int columnCount = sheet.getRow(0).getLastCellNum();  
            try {  
                Row row = sheet.createRow(rowCount);     //最新要添加的一行  
                //通过反射获得object的字段,对应表头插入  
                // 获取该对象的class对象  
                Class class_ = object.getClass();  
                // 获得表头行对象  
                hssfRow titleRow = sheet.getRow(0);  
                if(titleRow!=null){  
                    for (int columnIndex = 0; columnIndex < columnCount; columnIndex++) {  //遍历表头  
                        String title = titleRow.getCell(columnIndex).toString().trim().toString().trim();  
                        String UTitle = Character.toupperCase(title.charat(0))+ title.substring(1,title.length()); // 使其首字母大写;  
                        String methodName  = "get"+UTitle;  
                        Method method = class_.getDeclaredMethod(methodName); // 设置要执行的方法  
                        String data = method.invoke(object).toString(); // 执行该get方法,即要插入的数据  
                        Cell cell = row.createCell(columnIndex);  
                        cell.setCellValue(data);  
                    }  
                }  
      
                out = new FileOutputStream(fileDir);  
                workbook.write(out);  
            } catch (Exception e) {  
                e.printstacktrace();  
            } finally {    
                try {    
                    out.close();    
                } catch (IOException e) {    
                    e.printstacktrace();  
                }    
            }    
        }  
        /** 
         * 读取excel表中的数据. 
         *  
         * @param fileDir    文件路径    
         * @param sheetName 表格索引(EXCEL 是多表文档,所以需要输入表索引号,如sheet1) 
         * @param object   object 
         */  
        public List readFromExcel(String fileDir,Object object) {  
            //创建workbook  
            File file = new File(fileDir);  
            try {  
                workbook = new hssfWorkbook(new FileInputStream(file));  
            } catch (FileNotFoundException e) {  
                e.printstacktrace();  
            } catch (IOException e) {  
                e.printstacktrace();  
            }  
      
            List result = new ArrayList();  
            // 获取该对象的class对象  
            Class class_ = object.getClass();  
            // 获得该类的所有属性  
            Field[] fields = class_.getDeclaredFields();  
      
            // 读取excel数据  
            // 获得指定的excel表  
            hssfSheet sheet = workbook.getSheet(sheetName);  
            // 获取表格的总行数  
            int rowCount = sheet.getLastRowNum() + 1; // 需要加一  
            System.out.println("rowCount:"+rowCount);  
            if (rowCount < 1) {  
                return result;  
            }  
            // 获取表头的列数  
            int columnCount = sheet.getRow(0).getLastCellNum();  
            // 读取表头信息,确定需要用的方法名---set方法  
            // 用于存储方法名  
            String[] methodNames = new String[columnCount]; // 表头列数即为需要的set方法个数  
            // 用于存储属性类型  
            String[] fieldTypes = new String[columnCount];  
            // 获得表头行对象  
            hssfRow titleRow = sheet.getRow(0);  
            // 遍历  
            for (int columnIndex = 0; columnIndex < columnCount; columnIndex++) { // 遍历表头列  
                String data = titleRow.getCell(columnIndex).toString(); // 某一列的内容  
                String Udata = Character.toupperCase(data.charat(0))  
                        + data.substring(1,data.length()); // 使其首字母大写  
                methodNames[columnIndex] = "set" + Udata;  
                for (int i = 0; i < fields.length; i++) { // 遍历属性数组  
                    if (data.equals(fields[i].getName())) { // 属性与表头相等  
                        fieldTypes[columnIndex] = fields[i].getType().getName(); // 将属性类型放到数组中  
                    }  
                }  
            }  
            // 逐行读取数据 从1开始 忽略表头  
            for (int rowIndex = 1; rowIndex < rowCount; rowIndex++) {  
                // 获得行对象  
                hssfRow row = sheet.getRow(rowIndex);  
                if (row != null) {  
                    Object obj = null;  
                    // 实例化该泛型类的对象一个对象  
                    try {  
                        obj = class_.newInstance();  
                    } catch (Exception e1) {  
                        e1.printstacktrace();  
                    }  
      
                    // 获得本行中各单元格中的数据  
                    for (int columnIndex = 0; columnIndex < columnCount; columnIndex++) {  
                        String data = row.getCell(columnIndex).toString();  
                        // 获取要调用方法的方法名  
                        String methodName = methodNames[columnIndex];  
                        Method method = null;  
                        try {  
                            // 这部分可自己扩展  
                            if (fieldTypes[columnIndex].equals("java.lang.String")) {  
                                method = class_.getDeclaredMethod(methodName,String.class); // 设置要执行的方法--set方法参数为String  
                                method.invoke(obj,data); // 执行该方法  
                            } else if (fieldTypes[columnIndex].equals("int")) {  
                                method = class_.getDeclaredMethod(methodName,int.class); // 设置要执行的方法--set方法参数为int  
                                double data_double = Double.parseDouble(data);  
                                int data_int = (int) data_double;  
                                method.invoke(obj,data_int); // 执行该方法  
                            }  
                        } catch (Exception e) {  
                            e.printstacktrace();  
                        }  
                    }  
                    result.add(obj);  
                }  
            }  
            return result;  
        }  
          
          
        public static void main(String[] args) {  
            ExcelManage em = new ExcelManage();  
            //判断文件是否存在  
            System.out.println(em.fileExist("E:/test2.xls"));  
            //创建文件  
            String title[] = {"id","name","password"};  
            em.createExcel("E:/test2.xls","sheet1",title);  
            //判断sheet是否存在  
            System.out.println(em.sheetExist("E:/test2.xls","sheet1"));  
            //写入到excel  
            User user = new User();  
            user.setId(5);  
            user.setName("qwer");  
            user.setPassword("zxcv");  
            User user3 = new User();  
            user3.setId(6);  
            user3.setName("qwerwww");  
            user3.setPassword("zxcvwww");  
            em.writetoExcel("E:/test2.xls",user);  
            em.writetoExcel("E:/test2.xls",user3);  
            //读取excel  
            User user2 = new User();  
            List list = em.readFromExcel("E:/test2.xls",user2);  
            for (int i = 0; i < list.size(); i++) {  
                User newUser = (User) list.get(i);  
                System.out.println(newUser.getId() + " " + newUser.getName() + " "  
                        + newUser.getpassword());  
            }  
            //删除文件  
            //System.out.println(em.deleteExcel("E:/test2.xls"));  
        }  
      
    }  

下面是用于测试的一个bean类:
    package module.system.common;  
      
    public class User {  
        private int id;  
        private String name;  
        private String password;  
      
        public int getId() {  
            return id;  
        }  
      
        public void setId(int id) {  
            this.id = id;  
        }  
      
        public String getName() {  
            return name;  
        }  
      
        public void setName(String name) {  
            this.name = name;  
        }  
      
        public String getpassword() {  
            return password;  
        }  
      
        public void setPassword(String password) {  
            this.password = password;  
        }  
      
    }  

注意:在创建excel时,需要传入一个包含表头信息的数组,该数组中的内容必须对应bean类的属性值(数量可以不一样,但拼写和大小写必须一致)

来自:http://blog.csdn.net/u012116457/article/details/46325245

以上是小编(jb51.cc)为你收集整理的全部代码内容,希望文章能够帮你解决所遇到的程序开发问题。

如果觉得小编网站内容还不错,欢迎将小编网站推荐给程序员好友。

我们今天的关于哪个是用Java读取大型excel文件的最佳API?java读取大量excel的分享就到这里,谢谢您的阅读,如果想了解更多关于c# – 解析大型Excel文件列表失败、java – 在groovy中读取Excel文件的最简单方法?、Java利用jxl.jar操作Excel文件的方法——把两列相同的数据扫描输出到新的Excel文件中、java处理Excel文件---excel文件的创建,删除,写入,读取的相关信息,可以在本站进行搜索。

在本文中,我们将详细介绍如何在Java的各个方面,并为您提供关于Android中从AppEngine解析DateTime属性?的相关解答,同时,我们也将为您带来关于Android Android早期Java 8之前的ZonedDateTime到Date、Android java.time.LocalDateTime、android – 格式化DateUtils.getRelativeDateTimeString、Android-DateTimeAndroidUtil-工具类的有用知识。

本文目录一览:

如何在Java(Android)中从AppEngine解析DateTime属性?(java解析apk)

如何在Java(Android)中从AppEngine解析DateTime属性?(java解析apk)

我需要解析Java(Android)中来自AppEngine的DateTime字符串。该字符串如下所示:2011-07-2617:21:00+01:00。它是某种标准格式吗?有没有比使用custom更简单的方法SimpleDateFormat

答案1

小编典典

SimpleDateFormat非常简单,除了日期字符串由于其中的最后一个而有些偏离:。只需替换:并使用以下模式即可:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:ss:mmZ");String dateStr = "2011-07-26 17:21:00+0100";System.out.println(sdf.parse(dateStr));

Android Android早期Java 8之前的ZonedDateTime到Date

Android Android早期Java 8之前的ZonedDateTime到Date

我试图替换该ZonedDateTime.toInstant方法,因为该方法仅适用于Android的API 26。
但是我的应用程序应该支持
API19 。我想将ZonedDateTime转换为Date,以便执行以下操作:

final Calendar calendar = Calendar.getInstance();calendar.setTime(new Date());final long millis = calendar.getTimeInMillis();

我要实现的目标如下:
我想计算当前日期与另一个日期之间的时差(以秒,分钟,小时为单位),以可能的最高单位获胜,因此我将得到例如5 days ago结果。

答案1

小编典典

解决方案(ThreeTen-Backport库):
运行良好,我已经在KitKat模拟器上进行了尝试。

private static final ChronoUnit[] chronoUnits = {ChronoUnit.YEARS, ChronoUnit.MONTHS, ChronoUnit.DAYS, ChronoUnit.HOURS, ChronoUnit.MINUTES, ChronoUnit.SECONDS};private static final Map<ChronoUnit, Integer> chronoUnitPluralIdMap = new HashMap<ChronoUnit, Integer>() {{    put(ChronoUnit.YEARS, R.plurals.chrono_unit_years_ago);    put(ChronoUnit.MONTHS, R.plurals.chrono_unit_months_ago);    put(ChronoUnit.DAYS, R.plurals.chrono_unit_days_ago);    put(ChronoUnit.HOURS, R.plurals.chrono_unit_hours_ago);    put(ChronoUnit.MINUTES, R.plurals.chrono_unit_minutes_ago);    put(ChronoUnit.SECONDS, R.plurals.chrono_unit_seconds_ago);}};public static String getTimeStringUntilNowFromUTC(Context context, String utcDate) {    Instant now = Instant.now(Clock.systemUTC());    Instant then = Instant.parse(utcDate);    for (ChronoUnit chronoUnit : chronoUnits) {        if (then.isSupported(chronoUnit)) {            long units = chronoUnit.between(then, now);            if (units > 0) {                //noinspection ConstantConditions                return context.getResources().getQuantityString(chronoUnitPluralIdMap.get(chronoUnit), (int)units, (int)units);            }        }    }    return "-";}public static String getTimeBetweenTwoDates(Context context, String date1, String date2) {    Instant date1Instant = Instant.parse(date1);    Instant date2Instant = Instant.parse(date2);    final long seconds = ChronoUnit.SECONDS.between(date1Instant, date2Instant);    return getMinutesSecondsString(context, seconds);}

Android java.time.LocalDateTime

Android java.time.LocalDateTime

我正在编写一个Android应用程序,它应该通过我在服务器端开发的HTTP REST API接收java.time.LocalDateTime对象.

问题是Android仍然在Java 7中,而java.time仅在Java 8中可用.

话虽如此,在Android中表示包含日期和时间的变量的最佳方式是什么?我不想使用sql.timestamp.

谢谢!

解决方法:

为什么要使用Java 8之前的日期或日历,而Joda-time的Android版本(非常接近Java8日期)可用?

以下是GIT回购/网站的更多信息:

https://github.com/dlew/joda-time-android

android – 格式化DateUtils.getRelativeDateTimeString

android – 格式化DateUtils.getRelativeDateTimeString

我有这样的代码
DateUtils.getRelativeDateTimeString(context,due,DateUtils.MINUTE_IN_MILLIS,DateUtils.WEEK_IN_MILLIS,0)

这是输出格式化的字符串

in 23 hours,6:18am

我对android documentation这个方法不太了解.

有没有一个内置的方式来剥离时间或更改逗号更多的句子像?

“23小时”或“上午6时18分23时30分”优于目前的产出.

谢谢.

解决方法

我用了不同的方法,得到了我想要的“23小时”的结果
DateUtils.getRelativeTimeSpanString(due,Now,DateUtils.SECOND_IN_MILLIS)

Android-DateTimeAndroidUtil-工具类

Android-DateTimeAndroidUtil-工具类

DateTimeAndroidUtil-工具类 是关于时间日前相关的公用方法;

 

package liudeli.mynetwork01.utils;

import android.util.Log;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

/**
 * @Author Liudeli
 * @Describe:时间相关工具类
 */
public class DateTimeAndroidUtil {

    private DateTimeAndroidUtil(){}

    /**
     * 枚举日期格式
     */
    public enum DatePattern{
        /**
         * 格式:"yyyy-MM-dd HH:mm:ss"
         */
        ALL_TIME{public String getValue(){return "yyyy-MM-dd HH:mm:ss";}},
        /**
         * 格式:"yyyy-MM"
         */
        ONLY_MONTH{public String getValue(){return "yyyy-MM";}},
        /**
         * 格式:"yyyy-MM-dd"
         */
        ONLY_DAY{public String getValue(){return "yyyy-MM-dd";}},
        /**
         * 格式:"yyyy-MM-dd HH"
         */
        ONLY_HOUR{public String getValue(){return "yyyy-MM-dd HH";}},
        /**
         * 格式:"yyyy-MM-dd HH:mm"
         */
        ONLY_MINUTE{public String getValue(){return "yyyy-MM-dd HH:mm";}},
        /**
         * 格式:"MM-dd"
         */
        ONLY_MONTH_DAY{public String getValue(){return "MM-dd";}},
        /**
         * 格式:"MM-dd HH:mm"
         */
        ONLY_MONTH_SEC{public String getValue(){return "MM-dd HH:mm";}},
        /**
         * 格式:"HH:mm:ss"
         */
        ONLY_TIME{public String getValue(){return "HH:mm:ss";}},
        /**
         * 格式:"HH:mm"
         */
        ONLY_HOUR_MINUTE{public String getValue(){return "HH:mm";}};
        public abstract String getValue();
    }

    /**
     * 获取当前时间
     * @return    返回当前时间,格式2017-05-04    10:54:21
     */
    public static String getNowDate(DatePattern pattern){
        String dateString = null;
        Calendar calendar = Calendar.getInstance();
        Date dateNow = calendar.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat(pattern.getValue(),Locale.CHINA);
        dateString = sdf.format(dateNow);
        return dateString;
    }

    /**
     * 将一个日期字符串转换成Data对象
     * @param dateString    日期字符串
     * @param pattern        转换格式
     * @return    返回转换后的日期对象
     */
    public static Date stringToDate(String dateString, DatePattern pattern){
        Date date = null;
        SimpleDateFormat sdf = new SimpleDateFormat(pattern.getValue(),Locale.CHINA);
        try {
            date = sdf.parse(dateString);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }

    /**
     * 将date转换成字符串
     * @param date    日期
     * @param pattern    日期的目标格式
     * @return
     */
    public static String dateToString(Date date, DatePattern pattern){
        String string = "";
        SimpleDateFormat sdf = new SimpleDateFormat(pattern.getValue(), Locale.CHINA);
        string = sdf.format(date);
        return string;
    }

    /**
     * 获取指定日期周几
     * @param date    指定日期
     * @return
     * 返回值为: "周日", "周一", "周二", "周三", "周四", "周五", "周六"
     */
    public static String getWeekOfDate(Date date){
        String[] weekDays = { "周日", "周一", "周二", "周三", "周四", "周五", "周六" };
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int week = calendar.get(Calendar.DAY_OF_WEEK) - 1;
        if (week < 0)
            week = 0;
        return weekDays[week];
    }

    /**
     * 获取指定日期对应周几的序列
     * @param date    指定日期
     * @return    周一:1    周二:2    周三:3    周四:4    周五:5    周六:6    周日:7
     */
    public static int getIndexWeekOfDate(Date date){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int index = calendar.get(Calendar.DAY_OF_WEEK);
        if(index == 1){
            return 7;
        }else{
            return --index;
        }
    }

    /**
     * 返回当前月份
     * @return
     */
    public static int getNowMonth(){
        Calendar calendar = Calendar.getInstance();
        return calendar.get(Calendar.MONTH) + 1;
    }

    /**
     * 获取当前月号
     * @return
     */
    public static int getNowDay(){
        Calendar calendar = Calendar.getInstance();
        return calendar.get(Calendar.DATE);
    }

    /**
     * 获取当前年份
     * @return
     */
    public static int getNowYear(){
        Calendar calendar = Calendar.getInstance();
        return calendar.get(Calendar.YEAR);
    }

    /**
     * 获取本月份的天数
     * @return
     */
    public static int getNowDaysOfMonth(){
        Calendar calendar = Calendar.getInstance();
        return daysOfMonth(calendar.get(Calendar.YEAR),calendar.get(Calendar.DATE) + 1);
    }

    /**
     * 获取指定月份的天数
     * @param year    年份
     * @param month    月份
     * @return    对应天数
     */
    public static int daysOfMonth(int year,int month){
        switch(month){
            case 1:
            case 3:
            case 5:
            case 7:
            case 8:
            case 10:
            case 12:
                return 31;
            case 4:
            case 6:
            case 9:
            case 11:
                return 30;
            case 2:
                if((year % 4 ==0 && year % 100 == 0) || year % 400 != 0){
                    return 29;
                }else{
                    return 28;
                }
            default:
                return -1;
        }
    }

    /**
     * 获取当前时间
     * @return
     */
    public static String getNowTime(){
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date(System.currentTimeMillis());
        return simpleDateFormat.format(date);
    }

    /**
     * 获取当前时间
     * @return
     */
    public static String getThisTiem() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");// HH:mm:ss
        // 获取当前时间
        Date date = new Date(System.currentTimeMillis());
        return simpleDateFormat.format(date);
    }

    /**
     * 获取时间戳
     *
     * @return 获取时间戳
     */
    public static String getTimeString() {
        SimpleDateFormat df = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
        Calendar calendar = Calendar.getInstance();
        return df.format(calendar.getTime());
    }

    /**
     * 获取时间戳
     *
     * @return 获取时间戳
     */
    public static String getTimeString2() {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar calendar = Calendar.getInstance();
        return df.format(calendar.getTime());
    }

    /**
     * 时间转换为时间戳
     * @param time:需要转换的时间
     * @return
     */
    public static String dateToStamp(String time)  {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = null;
        try {
            date = simpleDateFormat.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        long ts = date.getTime();
        return String.valueOf(ts);
    }

    /**
     * 时间戳转换为字符串
     * @param time:时间戳
     * @return
     */
    public static String times(String time) {
        SimpleDateFormat sdr = new SimpleDateFormat("yyyy年MM月dd日 HH时mm分");
        @SuppressWarnings("unused")
        long lcc = Long.valueOf(time);
        int i = Integer.parseInt(time);
        String times = sdr.format(new Date(i * 1000L));
        return times;

    }
    /**
     *获取距现在某一小时的时刻
     * @param hour hour=-1为上一个小时,hour=1为下一个小时
     * @return
     */
    public static String getLongTime(int hour){
        Calendar c = Calendar.getInstance(); // 当时的日期和时间
        int h; // 需要更改的小时
        h = c.get(Calendar.HOUR_OF_DAY) - hour;
        c.set(Calendar.HOUR_OF_DAY, h);
        SimpleDateFormat df = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
        Log.v("time",df.format(c.getTime()));
        return df.format(c.getTime());
    }
    /**
     * 比较时间大小
     * @param str1:要比较的时间
     * @param str2:要比较的时间
     * @return
     */
    public static boolean isDateOneBigger(String str1, String str2) {
        boolean isBigger = false;
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
        Date dt1 = null;
        Date dt2 = null;
        try {
            dt1 = sdf.parse(str1);
            dt2 = sdf.parse(str2);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (dt1.getTime() > dt2.getTime()) {
            isBigger = true;
        } else if (dt1.getTime() < dt2.getTime()) {
            isBigger = false;
        }
        return isBigger;
    }

    /**
     * 当地时间 ---> UTC时间
     * @return
     */
    public static String Local2UTC(){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        sdf.setTimeZone(TimeZone.getTimeZone("gmt"));
        String gmtTime = sdf.format(new Date());
        return gmtTime;
    }

    /**
     * UTC时间 ---> 当地时间
     * @param utcTime   UTC时间
     * @return
     */
    public static String utc2Local(String utcTime) {
        SimpleDateFormat utcFormater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//UTC时间格式
        utcFormater.setTimeZone(TimeZone.getTimeZone("UTC"));
        Date gpsUTCDate = null;
        try {
            gpsUTCDate = utcFormater.parse(utcTime);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        SimpleDateFormat localFormater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//当地时间格式
        localFormater.setTimeZone(TimeZone.getDefault());
        String localTime = localFormater.format(gpsUTCDate.getTime());
        return localTime;
    }
}

 

我们今天的关于如何在JavaAndroid中从AppEngine解析DateTime属性?的分享就到这里,谢谢您的阅读,如果想了解更多关于Android Android早期Java 8之前的ZonedDateTime到Date、Android java.time.LocalDateTime、android – 格式化DateUtils.getRelativeDateTimeString、Android-DateTimeAndroidUtil-工具类的相关信息,可以在本站进行搜索。

在本文中,我们将为您详细介绍Google Hangouts Meet API文档的相关知识,并且为您解答关于google docs api的疑问,此外,我们还会提供一些关于android – 在哪里向Google报告API错误? (Google Nearby Messages API)、android – 尝试从Google Cloud Messaging消息更改Google Maps v2 Api上的标记时的非法状态异常、android-YouTube API:com.google.api.client.googleapis.json.GoogleJsonResponseException:禁止使用403、android-在Google Hangout API中处理音频数据的有用信息。

本文目录一览:

Google Hangouts Meet API文档(google docs api)

Google Hangouts Meet API文档(google docs api)

改善这个问题

我正在寻找Google Hangouts Meet的原始api文档。我注意到一个机器人 挂断
https://github.com/tdryer/hangups使用以下网址:

https://clients6.google.com/chat/v1/#{endpoint}https://clients6.google.com/chat/v1/conversations/sendchatmessagehttps://clients6.google.com/chat/v1/conversations/removeuserhttps://clients6.google.com/chat/v1/conversations/createconversation

但是我找不到任何参考。

答案1

小编典典

您所指向的回购协议说明了他们从何处获得的信息:

与之前的Google
Talk不同,环聊使用专有的,不可互操作的协议。挂断是通过对该协议进行反向工程来实现的,该协议使其能够支持诸如组消息传递之类的功能,这些功能在通过XMPP连接的客户端中不可用。

基本上,该库的作者只是撤消了这些REST api调用。大概是通过使用实际的google视频群聊,然后查看网络对其产生的影响。

我不相信google对此有任何文档。

android – 在哪里向Google报告API错误? (Google Nearby Messages API)

android – 在哪里向Google报告API错误? (Google Nearby Messages API)

我真的试图找到将我的错误报告发布到谷歌有关新的Google Nearby Messages API的最佳位置,但我没有找到任何合适的地方.

我们最近尝试了新的API,我们对它非常满意,它运行良好,我们的问题不是一个功能错误.我们的许多用户使用匈牙利语的应用程序,并且API的批准对话框不适合我们在小屏幕(Android设备)上设计.

这就是英语对话框的样子:

enter image description here

这是匈牙利人:

enter image description here

如您所见,对话框中仅缺少“允许”按钮,这使我们无法使用此功能发布更新的软件.我可以在哪里为Google的开发人员发布此问题?

我真的不想把它发布到错误的地方,例如:https://code.google.com/p/play-games-platform/issues/list

解决方法

也许您可以在GitHub上查看googlesamples存储库.
有一个适用于Android附近和iOS附近.

https://github.com/googlesamples?utf8=✓&安培;查询=附近
https://github.com/googlesamples/android-nearby/issues

android – 尝试从Google Cloud Messaging消息更改Google Maps v2 Api上的标记时的非法状态异常

android – 尝试从Google Cloud Messaging消息更改Google Maps v2 Api上的标记时的非法状态异常

我正在编写一个 Android应用程序,我在Google地图上有标记,应该更改为我通过GCM收到的位置.
我有一个全局静态列表,我将标记与id和位置一起保存.
当我收到消息时,我可以在GCMBaseIntentService中更改列表中对象的位置,但是当我想执行以下代码时:
mMarker.setPosition(new LatLng(member.getLatitude(),member.getLongitude()));

我得到以下例外:

01-13 18:52:38.118: E/AndroidRuntime(7605): FATAL EXCEPTION: IntentService[GCMIntentService-1041237551356-1]
    01-13 18:52:38.118: E/AndroidRuntime(7605): java.lang.IllegalStateException: Not on the main thread
    01-13 18:52:38.118: E/AndroidRuntime(7605):     at maps.am.r.b(UnkNown Source)
    01-13 18:52:38.118: E/AndroidRuntime(7605):     at maps.ar.d.b(UnkNown Source)
    01-13 18:52:38.118: E/AndroidRuntime(7605):     at maps.y.ae.addMarker(UnkNown Source)
    01-13 18:52:38.118: E/AndroidRuntime(7605):     at com.google.android.gms.maps.internal.IGoogleMapDelegate$Stub.onTransact(IGoogleMapDelegate.java:167)
    01-13 18:52:38.118: E/AndroidRuntime(7605):     at android.os.Binder.transact(Binder.java:279)
    01-13 18:52:38.118: E/AndroidRuntime(7605):     at com.google.android.gms.maps.internal.IGoogleMapDelegate$a$a.addMarker(UnkNown Source)
    01-13 18:52:38.118: E/AndroidRuntime(7605):     at com.google.android.gms.maps.GoogleMap.addMarker(UnkNown Source)
    01-13 18:52:38.118: E/AndroidRuntime(7605):     at com.example.MapViewActivity.showMember(MapViewActivity.java:529)
    01-13 18:52:38.118: E/AndroidRuntime(7605):     at com.example.MapViewActivity.updateMember(MapViewActivity.java:417)
    01-13 18:52:38.118: E/AndroidRuntime(7605):     at com.example.MapViewActivity.updateMembers(MapViewActivity.java:410)
    01-13 18:52:38.118: E/AndroidRuntime(7605):     at com.example.pushnotifications.GCMIntentService.onMessage(GCMIntentService.java:75)
    01-13 18:52:38.118: E/AndroidRuntime(7605):     at com.google.android.gcm.GCMBaseIntentService.onHandleIntent(GCMBaseIntentService.java:223)
    01-13 18:52:38.118: E/AndroidRuntime(7605):     at android.app.IntentService$ServiceHandler.handleMessage(IntentService.java:59)
    01-13 18:52:38.118: E/AndroidRuntime(7605):     at android.os.Handler.dispatchMessage(Handler.java:99)
    01-13 18:52:38.118: E/AndroidRuntime(7605):     at android.os.Looper.loop(Looper.java:130)
    01-13 18:52:38.118: E/AndroidRuntime(7605):     at android.os.HandlerThread.run(HandlerThread.java:60)

我尝试在地图上添加一个按钮来刷新所有标记(具有完全相同的代码),并且工作正常.
所以不知何故问题是GCM是在不同的线程或类似的东西中执行的,似乎我无法从不同的线程中更改标记…

我尝试了一个丑陋的解决方案:每秒刷新所有标记.
但是从MapViewActivity创建一个线程会产生相同的异常:

private Thread MarkerUpdater = new Thread(
    new Runnable() {
        public void run() {
            while(true) {
                updateMembers();
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // Todo Auto-generated catch block
                    e.printstacktrace();
                }
            }
        }
    });

也许有人知道一个好的解决方案会是什么样子?

解决方法

您需要获取主UI线程的处理程序并在那里发布runnable.
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable(){ 
   // your UI code here 
}

您在Runnable中从服务中引用的任何变量都必须是最终的.既然你说你正在以全局/静态方式共享数据,你应该没问题.

android-YouTube API:com.google.api.client.googleapis.json.GoogleJsonResponseException:禁止使用403

android-YouTube API:com.google.api.client.googleapis.json.GoogleJsonResponseException:禁止使用403

我是YouTube API的新手.我已经从Eclipse的github下载并导入了yt-direct-lite youtube android项目.一切顺利.但是,当我运行该项目时,它会吐出/弹出以下错误消息:

[Error] Access not configured: The API (youTube Data API) is not enabled for your project. Please use google developer console to update your configuration.

但是,我已经打开了Google Api以及YouTube Data API v3.

另外,我已经生成了API密钥.一切都很好,但是要登录该项目中的Google / Gmail帐户.同样,在异常以下触发.

02-04 15:06:38.553: E/TetsProject(8413): Error
02-04 15:06:38.553: E/TetsProject(8413): com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 Forbidden
02-04 15:06:38.553: E/TetsProject(8413): {
02-04 15:06:38.553: E/TetsProject(8413):   "code": 403,
02-04 15:06:38.553: E/TetsProject(8413):   "errors": [
02-04 15:06:38.553: E/TetsProject(8413):     {
02-04 15:06:38.553: E/TetsProject(8413):       "domain": "usageLimits",
02-04 15:06:38.553: E/TetsProject(8413):       "message": "Access Not Configured. The API (YouTube Data API) is not enabled for your project. Please use the Google Developers Console to update your configuration.",
02-04 15:06:38.553: E/TetsProject(8413):       "reason": "accessNotConfigured",
02-04 15:06:38.553: E/TetsProject(8413):       "extendedHelp": "https://console.developers.google.com"
02-04 15:06:38.553: E/TetsProject(8413):     }
02-04 15:06:38.553: E/TetsProject(8413):   ],
02-04 15:06:38.553: E/TetsProject(8413):   "message": "Access Not Configured. The API (YouTube Data API) is not enabled for your project. Please use the Google Developers Console to update your configuration."
02-04 15:06:38.553: E/TetsProject(8413): }
02-04 15:06:38.553: E/TetsProject(8413):    at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:113)
02-04 15:06:38.553: E/TetsProject(8413):    at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:40)
02-04 15:06:38.553: E/TetsProject(8413):    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest$1.interceptResponse(AbstractGoogleClientRequest.java:312)
02-04 15:06:38.553: E/TetsProject(8413):    at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:1049)
02-04 15:06:38.553: E/TetsProject(8413):    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:410)
02-04 15:06:38.553: E/TetsProject(8413):    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:343)
02-04 15:06:38.553: E/TetsProject(8413):    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:460)
02-04 15:06:38.553: E/TetsProject(8413):    at com.google.ytdl.MainActivity$3.doInBackground(MainActivity.java:417)
02-04 15:06:38.553: E/TetsProject(8413):    at com.google.ytdl.MainActivity$3.doInBackground(MainActivity.java:1)
02-04 15:06:38.553: E/TetsProject(8413):    at android.os.AsyncTask$2.call(AsyncTask.java:287)
02-04 15:06:38.553: E/TetsProject(8413):    at java.util.concurrent.FutureTask.run(FutureTask.java:234)
02-04 15:06:38.553: E/TetsProject(8413):    at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
02-04 15:06:38.553: E/TetsProject(8413):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
02-04 15:06:38.553: E/TetsProject(8413):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
02-04 15:06:38.553: E/TetsProject(8413):    at java.lang.Thread.run(Thread.java:856)
02-04 15:06:38.633: I/brcm-gr(8413): [gralloc_lock]: new usage 0x933

我不知道这是怎么回事?

解决方法:

经过一些RnD,我已经解决了这个问题.事情是第一
启用youtubeapi v3和Google Api,然后转到凭据,然后生成Android API密钥.

首先通过单击“创建新的客户端ID”来生成客户端ID
然后选择已安装的应用程序,然后选择Android.在下面,您必须提供应用程序的确切程序包名称和sha1指纹,然后选择深度链接并最后创建客户端ID.

创建完成后,请为播放器youtube视频创建android api键.然后您的api密钥将起作用.请记住,填写软件包名称时,软件包名称将与eclipe或studio中的应用程序相同.

如果在创建客户端ID后更改了包名称,则密钥将不起作用.请记住,pckg名称在此处受限制,并且不必更改.

android-在Google Hangout API中处理音频数据

android-在Google Hangout API中处理音频数据

是否可以使用Google hangout API拦截音频数据?我使用适用于Android的g hangout编写了一个应用,我想处理音频.首先,我想对语音进行降噪,然后使用语音转文字(例如google搜索,狮身人面像)进行基本的语音命令.

因为我可以完全控制android应用,所以对我来说没关系,如果我可以通过环聊中的音频数据进行回调,或者可以使用android AudioRecorder录制音频,然后以某种方式将这些数据转发到google hangout(尽管后一种解决方案会会更好,因为我们可以在android设备上进行降噪).实际上,对于在该API阶段可以使用的任何可行的解决方法,我都会感到满意.

解决方法:

Hangouts API不会帮助您开发此功能.

您需要的是平台无关的API,用于访问环聊数据.该API旨在解决其他问题.它允许您编写在桌面Web浏览器上运行的环聊画布内运行的HTML / JavaScript应用程序.

关于Google Hangouts Meet API文档google docs api的介绍现已完结,谢谢您的耐心阅读,如果想了解更多关于android – 在哪里向Google报告API错误? (Google Nearby Messages API)、android – 尝试从Google Cloud Messaging消息更改Google Maps v2 Api上的标记时的非法状态异常、android-YouTube API:com.google.api.client.googleapis.json.GoogleJsonResponseException:禁止使用403、android-在Google Hangout API中处理音频数据的相关知识,请在本站寻找。

本文标签: