简体   繁体   中英

Jython sending array of java File objects to java class from python

I'm having what I believe is a python string issue. The goal is to send a java class an array of File objects from python/Jython. I'm getting a error related to the string path sent to the File constructor. I believe it is because i can't seem to get rid of the double slash. python code below:

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)

I get the error "TypeError: can't convert 'C:\\..." to Java.io.File I have also tried .replace('\\\\','\\') in the comprehension to no avail. It works when i just type out the full path in a string and send it to a java.File object. The issue seems to be I can't get rid of the \\'s in the path using the comprehension. Any help would be greatly appreciated. thank you!

The problem here is that onlyfiles is a list of strings ( <type 'str'> ), not a list of files. Recall that normally in Python file paths are handled simply as strings and that the os.path.* methods take a string and return a string.

Therefore you need to make Java File s out of the strings. One way is like this:

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

A full example therefore looks like this (Note I added the missing imports):

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM