2

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!

1 Answer 1

2

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 Files 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)
Sign up to request clarification or add additional context in comments.

1 Comment

It worked great thank you! i had misunderstood the docs. array() doesn't make a list of Files by running your list of strings through a File constructor. It just defines the type of the array. got it!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.