java.lang.IllegalArgumentException:包含一个path分隔符

我的代码中有一个文件名:

String NAME_OF_FILE="//sdcard//imageq.png"; FileInputStream fis =this.openFileInput(NAME_OF_FILE); // 2nd line 

我在第二行发生错误:

05-11 16:49:06.355:错误/ AndroidRuntime(4570):引起:java.lang.IllegalArgumentException:文件//sdcard//imageq.png包含一个path分隔符

我也尝试过这种格式:

 String NAME_OF_FILE="/sdcard/imageq.png"; 

此方法在应用程序的专用数据区域中打开一个文件。 您无法使用此方法在此区域的子目录中打开任何文件,也无法从其他区域打开任何文件。 所以直接使用FileInputStream的构造函数传递一个包含目录的path。

解决scheme是:

 FileInputStream fis = new FileInputStream (new File(NAME_OF_FILE)); // 2nd line 

openFileInput方法不接受path分隔符。

别忘了

 fis.close(); 

最后。

openFileInput()不接受path,只有一个文件名,如果你想访问一个path,使用File file = new File(path)和相应的FileInputStream

您不能直接使用目录分隔符的path,但是您必须为每个目录创build一个文件对象。

注:此代码使目录,你可能不需要…

 File file= context.getFilesDir(); file.mkdir(); String[] array=filePath.split("/"); for(int t=0; t< array.length -1 ;t++) { file=new File(file,array[t]); file.mkdir(); } File f=new File(file,array[array.length-1]); RandomAccessFileOutputStream rvalue = new RandomAccessFileOutputStream(f,append); 
 File file = context.getFilesDir(); file.mkdir(); String[] array = filePath.split("/"); for(int t = 0; t < array.length - 1; t++) { file = new File(file, array[t]); file.mkdir(); } File f = new File(file,array[array.length- 1]); RandomAccessFileOutputStream rvalue = new RandomAccessFileOutputStream(f, append); 

我通过在onCreate事件中创build一个目录来解决这种types的错误,然后通过在需要执行某些操作的方法中创build一个新的文件对象来访问该目录,例如保存或检索该目录中的文件,希望这有帮助!

  public class MyClass { private String state; public File myFilename; @Override protected void onCreate(Bundle savedInstanceState) {//create your directory the user will be able to find super.onCreate(savedInstanceState); if (Environment.MEDIA_MOUNTED.equals(state)) { myFilename = new File(Environment.getExternalStorageDirectory().toString() + "/My Directory"); if (!myFilename.exists()) { myFilename.mkdirs(); } } } public void myMethod { File fileTo = new File(myFilename.toString() + "/myPic.png"); // use fileTo object to save your file in your new directory that was created in the onCreate method } }