gpt4 book ai didi

java - 在android中读取文件。如何修复坏路径

转载 作者:行者123 更新时间:2023-12-01 15:03:25 26 4
gpt4 key购买 nike

我正在尝试读取 android 中的文件。我习惯在 java 中执行此操作,但在这里我收到 open failed enoent (no such file or directory) 错误。我不确定如何导入该文件。我应该将它放在与我的应用程序相同的目录中吗?现在它在我的桌面上。这是我的代码

package com.androidplot.fun;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadFile {
private String path;
public ReadFile(String file_path){
path = file_path;
}
public String[] OpenFile() throws IOException{
FileReader fr = new FileReader(path);
BufferedReader textReader = new BufferedReader(fr);
int numberOfLines = 3;
String[ ] textData = new String[numberOfLines];
int i;
for (i=0; i < numberOfLines; i++) {
textData[ i ] = textReader.readLine();
}
textReader.close( );
return textData;
}
int readLines() throws IOException{
FileReader file_to_read = new FileReader(path);
BufferedReader bf = new BufferedReader(file_to_read);

String aLine;
int numberOfLines = 0;
while (( aLine = bf.readLine()) != null){
numberOfLines++;
}
bf.close();
return numberOfLines;
}

}

这是我一直在使用的类。这就是我在主程序中使用的

try{
ReadFile file = new ReadFile("/Users/jonathon/Desktop/data.txt");
String[] aryLines = file.OpenFile();
int x;
for ( x=0; x < aryLines.length; i++ ) {
System.out.println( aryLines[ i ] ) ;
}
}
catch ( IOException e ) {
System.out.println( e.getMessage() );
}

最佳答案

此文件是否会与您的应用程序 bundle 在一起?如果是这样,您应该将其作为资源包含在内。这是 link以及一些有关如何实现这一目标的一般信息。

编辑:我刚刚查看了您的文件路径。在 Android 模拟器上运行的代码将无法访问您的 Windows 桌面。启动模拟器,将数据传输给它,然后让应用程序尝试从“手机”读取数据。

关于java - 在android中读取文件。如何修复坏路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13311528/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com