簡體   English   中英

Jython 將 java File 對象數組從 python 發送到 java 類

[英]Jython sending array of java File objects to java class from python

我遇到了我認為是 python 字符串問題的問題。 目標是從 python/Jython 向 java 類發送一個 File 對象數組。 我收到與發送到 File 構造函數的字符串路徑相關的錯誤。 我相信這是因為我似乎無法擺脫雙斜線。 下面的python代碼:

from java.io import File
from jarray import array

myPath ='C:\\something\\somethingElse'
onlyfiles = [ abspath(join(myPath,f)) for f in listdir(myPath) if isfile(join(myPath,f))]

jythonArray = array(onlyfiles, String)
temp=array(onlyfiles,File)

我收到錯誤“TypeError: can't convert 'C:\\...” to Java.io.File 我也試過 .replace('\\\\','\\') 在理解中無濟於事。 當我只是在字符串中輸入完整路徑並將其發送到 java.File 對象時,它就起作用了。 問題似乎是我無法使用理解來擺脫路徑中的 \\'s。 任何幫助將不勝感激。 謝謝你!

這里的問題是onlyfiles是一個字符串列表( <type 'str'> ),而不是一個文件列表。 回想一下,通常在 Python 中文件路徑被簡單地處理為字符串,並且os.path.*方法接受一個字符串並返回一個字符串。

因此,您需要從字符串中提取 Java File 一種方法是這樣的:

onlyjavafiles = [File(f) for f in onlyfiles]

因此,一個完整的示例如下所示(注意我添加了缺少的導入):

from java.io import File
from java.lang import String
from jarray import array, zeros
from os import listdir
from os.path import isfile, join, abspath

myPath = '/tmp'
onlyfiles = [abspath(join(myPath, f)) for f in listdir(myPath) if isfile(join(myPath, f))]
onlyjavafiles = [File(f) for f in onlyfiles]

jythonArray = array(onlyfiles, String)
temp = array(onlyjavafiles, File)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM