2011-05-11 80 views
64

我的代码中有一个文件名作为:java.lang.IllegalArgumentException异常:包含路径分隔符

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

我得到第2行错误:

05-11 16:49: 06.355:ERROR/AndroidRuntime(4570):java.lang.IllegalArgumentException异常:致文件//sdcard//imageq.png包含路径分隔

我尝试这样格式还:

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

回答

56

此方法打开应用程序的私有数据区中的文件不接受路径,只有文件名 。您无法使用此方法在此区域的子目录中或从其他区域打开任何文件。因此,直接使用FileInputStream的构造函数将路径传递给目录。

+15

请为此提供一些示例 –

+5

您的答案很混乱; OP正在使用FileInputStream – FracturedRetina

+2

提供示例 –

22

openFileInput(),如果你要访问的路径,使用File file = new File(path)和相应的FileInputStream

+26

将是巨大的,如果你提供了一些示例代码来实现这个! –

+2

@MuhammadBabar当然你需要代码,你不能总是编码没有人提供给你一个。检查文档也许? –

3

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

注:此代码目录,你可能不需要那么......

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); 
+4

什么? '文件f =新文件(fileDirPath); F。mkdirs();'请编辑 –

57

解决的办法是:

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

的openFileInput方法不接受路径分隔符。

不要在最后不忘

fis.close(); 

+0

考虑到可以像这样使用'FileInputStream',为什么选择使用'openFileInput'? –

+0

这可以帮助我很多。谢谢 –

+0

这应该是正确标记的答案,因为它提供了一个明确的例子。 – marienke

0
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); 
+0

与前一个答案相同。 – AnixPasBesoin

0

我通过在onCreate事件的目录,然后在需要做一些事情,如保存或检索文件在该目录中的方法创建一个新的文件对象访问目录解决这种类型的错误, 希望这可以帮助!

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 
} 
} 
0

我得到了上面的错误信息,同时试图访问使用openFileInput("/Dir/data.txt")方法与子目录Dir从内部存储中的文件。

使用上述方法无法访问子目录。

尝试类似:

FileInputStream fIS = new FileInputStream (new File("/Dir/data.txt")); 
相关问题