我的sdcard文件夹中有多个文本文件,我已经构建了一个允许用户选择所需文件的活动。
但是,我必须使用将文件路径传递给文件构造函数(参见第2行)。 textfile.java:
File sdcard = Environment.getExternalStorageDirectory();
//Get the text file
File file = new File(sdcard,"my/ans.txt");//line2
//ob.pathh
//Read text from file
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
}
我希望第二个参数即filepath存储为字符串 有什么方法可以让我选择完整的文件路径 我使用的代码如下:
AndroindApplication .java:
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class AndroindApplication extends ListActivity {
private List<String> item = null;
public List<String> path = null;
private String root="/";
private TextView myPath;
public String pathh;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sdcard);
myPath = (TextView)findViewById(R.id.path);
getDir("/sdcard/");
}
private void getDir(String dirPath)
{
myPath.setText("Location: " + dirPath);
item = new ArrayList<String>();
path = new ArrayList<String>();
File f = new File(dirPath);
File[] files = f.listFiles();
if(!dirPath.equals(root))
{
item.add(root);
path.add(root);
item.add("../");
path.add(f.getParent());
}
for(int i=0; i < files.length; i++)
{
File file = files[i];
path.add(file.getPath());
if(file.isDirectory())
item.add(file.getName() + "/");
else
item.add(file.getName());
}
ArrayAdapter<String> fileList =
new ArrayAdapter<String>(this, R.layout.row, item);
setListAdapter(fileList);
}
@Override
protected void onListItemClick(ListView l, View view, int position, long id) {
File file = new File(path.get(position));
pathh=path.get(position);
Log.e("path="+path,"dxgx");
if (file.isDirectory())
{
if(file.canRead())
getDir(path.get(position));
else
{
new AlertDialog.Builder(this)
.setIcon(R.drawable.icon)
.setTitle("[" + file.getName() + "] folder can't be read!")
.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
}).show();
}
}
else
{
Intent myIntent = new Intent(view.getContext(), textfile.class);//goes to textfile.java
startActivityForResult(myIntent, 0);
}
}
}
我需要获得绝对路径,以便我可以将其传递给
File file = new File(sdcard,"my/ans.txt");//line2
并且在必须打开新文件时不必在代码中指定文件路径
无论如何我可以从AndroidApplication.java获取它吗?
答案 0 :(得分:4)
如果我了解您的需求,可以使用getAbsolutePath()
方法获取文件的完整路径。
编辑:
存储您文件夹的路径,即
String myPath = sdcardEnvironment.getExternalStorageDirectory().getAbsolutePath() + "/my/";
然后以:
的形式访问文件File currentFile = new File(myPath + path.get(position));