2014-12-03 49 views
0

我试图运行从文本文件输入数据的android应用程序时,出现以下错误。 “java.io.fileNotFoundException:/File.txt:打开失败:ENOENT(无此文件或目录)”在Android应用程序中导入文本文件?

问题文件位于Eclipse项目文件夹中。 我也试过把它放在assets文件夹以及其他几个文件夹中。 这里是有问题的代码:

File file = new File("File.txt"); 
    TestOutput = new ArrayList<String>(); 
    String x = ""; 
    try 
    { 
     Scanner scanner = new Scanner(file); 
     while (sc.hasNextLine()) 
     { 
      x = sc.nextLine(); 
      TestOutput.add(x); 
     } 
     scanner.close(); 
    } 
    catch (FileNotFoundException e) 
    { 
     e.printStackTrace(); 
    } 

到目前为止,我已经尝试使用一个包装类无济于事,代码其中低于:

import java.io.File; 
import java.io.FileNotFoundException; 
import java.util.ArrayList; 
import java.util.Scanner; 


public class FileGet 
{ 

ArrayList<String> TestOutput = new ArrayList<String>(); 
public FileGet() { 

} 
public ArrayList<String> getFile() { 
    File file = new File("TestOutput.txt"); 
    TestOutput = new ArrayList<String>(); 
    try 
    { 
     Scanner scanner = new Scanner(file); 
     String x = ""; 
     while (scanner.hasNextLine()) 
     { 
      x = scanner.nextLine(); 
      TestOutput.add(x); 
     } 
     scanner.close(); 
    } 
    catch (FileNotFoundException e) 
    { 
     e.printStackTrace(); 
    } 
    return TestOutput; 
} 
} 

该代码工作的罚款外android应用程序。任何意见/反应将不胜感激。

+1

将该文件放入资产中,然后使用资产管理器使用该文件。然后您可以打开输入流到该文件进行读取。 – RaviVadera 2014-12-03 05:01:39

+0

谢谢!你有没有使用我可以阅读的资产管理器的例子? – Bob 2014-12-03 05:16:06

+0

你可以很容易地在谷歌上搜索,只需键入'从资产android中读取文本文件' – RaviVadera 2014-12-03 05:27:39

回答

1

试试这个,名为“line”的字符串是所有TextFile被读取的字符串。

将.txt文件放在/ resources/raw文件夹下。

InputStream is = getResources().openRawResource(R.raw.name_of_file); 
BufferedReader r = new BufferedReader(new InputStreamReader(is)); 
StringBuilder total = new StringBuilder(); 
String line = null; 
try { 
    while ((line = r.readLine()) != null) 
    total.append(line); 
} catch (IOException e) { 
    e.printStackTrace(); 
} 
line = total.toString(); 
相关问题