从Go到Android使用gomobile工具生成”.APK”文件后,文件无法识别。

huangapple go评论101阅读模式
英文:

File is not recognized after generating the ".APK" file from Go to Android using gomobile tool

问题

我正在一个项目中工作,需要使用gomobile工具从Golang代码库生成一个APK文件。
计划是能够在Android平板上运行它。
当我通过Android Studio在平板上安装apk文件时,会出现以下错误。

 E/Go: panic: open C:/Users/ash/OneDrive/Desktop/go-workSpace/src/Myproject/config.json: no such file or directory

然而,在错误消息中点击给定的路径后,Android Studio会打开它所抱怨找不到的文件(config.json)。

这是我在Go中的源代码:

exDir := "C:/Users/ash/OneDrive/Desktop/go-workSpace/src/Myproject/"
configFile, err := ioutil.ReadFile(filepath.Join(filepath.Dir(exDir), "config.json")) // 在可执行文件所在目录中查找配置文件

Check(err)

func Check(err error) {
	if err != nil {
		fmt.Println("Received generic error, panicking")
		fmt.Println(err)
		panic(err)
	}
}

有什么建议如何修复文件路径吗?

英文:

I am working on a project in which i need to generate an APK file form a Golang code base using gomobile tool.
the plan is to be able to run it on android tablet.
When I install the apk file on the tablet, through the Android Studio I get the following error.

 E/Go: panic: open C:/Users/ash/OneDrive/Desktop/go-workSpace/src/Myproject/config.json: no such file or directory

However, after clicking on the given path in the error message, the Android Studio opens the the file it is complaining to find (config.json)

Here is the source code I have in Go

exDir := "C:/Users/ash/OneDrive/Desktop/go-workSpace/src/Myproject/"    
configFile, err := ioutil.ReadFile(filepath.Join(filepath.Dir(exDir), "config.json")) // Look for the config file in the same directory as the executable
    
Check(err)

func Check(err error) {
	if err != nil {
		fmt.Println("Received generic error, panicking")
		fmt.Println(err)
		panic(err)
	}
}

Any suggestion how to fix the file path?

答案1

得分: 0

在查看了这个帖子之后,
这是官方的Go支持页面
所以,我认为我需要:

  1. 将所有文件移动到名为assets的目录中。
  2. assets目录被嵌入到".APK"中,可以通过Android代码库访问。
import "golang.org/x/mobile/asset"

jsonFile, errOpen := asset.Open(config.json)
if errOpen != nil {
    fmt.Println(errOpen)
}
defer jsonFile.Close()
buf, errRead := ioutil.ReadAll(jsonFile)
if errRead != nil {
    fmt.Println(errRead)
}
英文:

After reviewing this thread.
Here is the official go support page.
So, I think I need to

  1. move all the files into a directory called assets.
  2. The assets directory is embedding to the ".APK" can be accessed through Android code base.

> import "golang.org/x/mobile/asset"
>
> jsonFile, errOpen := asset.Open(config.json)
> if errOpen != nil {
> fmt.Println(errOpen)
> }
> defer jsonFile.Close()
> buf, errRead := ioutil.ReadAll(jsonFile)
> if errRead != nil {
> fmt.Println(errRead)
> }

huangapple
  • 本文由 发表于 2021年7月2日 01:05:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/68214286.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定