我正在尝试访问Android设备上的文本文件。我已成功写入并在我的代码中读取文件,但我希望能够访问该文件,以便我可以将其复制并移动到其他位置。
我的代码包含在下面,运行时没有错误。但是,我只是编写了大量编辑的基本代码,试图解决这个问题。
虽然未显示,但默认方法onCreate在方法中包含的默认代码之后按顺序运行createFile(),writeFile(“Hello File!”)和readFile()。
Context context = this;
String autoFileName = "AutoDataFile.txt";
File path;
File myFile;
String insideText = "NOTHING";
public void createFile(){
path = context.getFilesDir();
myFile = new File(path, autoFileName);
}
public void writeFile(String text){
try {
FileOutputStream stream = new FileOutputStream(myFile);
stream.write(text.getBytes());
stream.write(",".getBytes());
stream.write("Second input!".getBytes());
stream.close();
System.out.println("SUCCESS?: MAY HAVE WRITTEN TO FILE");
} catch (Exception e){
e.printStackTrace();
System.out.println("ERROR: DID NOT WRITE TO FILE");
}
}
public void readFile(){
try {
Scanner fileStream = new Scanner(myFile);
insideText += " " + fileStream.useDelimiter(",").nextLine();
System.out.println("SUCCESS?: MAY HAVE READ FROM FILE");
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("ERROR: DID NOT READ FROM FILE");
}
}
答案 0 :(得分:0)
你可以这样做:
到你的build.gradle
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
然后添加到您的清单
public void writeCSV(ArrayList<String> content) {
//Point a directory to the external storage
File exportDir = new File(Environment.getExternalStorageDirectory(), "");
if (!exportDir.exists()) {
exportDir.mkdirs();
}
//formatter for the date associated with the file name
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
//inner file to be the location of the csv
File csv = new File(exportDir, "csvdata_" + sdf.format(Calendar.getInstance().getTime()) + ".csv");
try {
//create the file and the writer which will append our data
csv.createNewFile();
CSVWriter writer = new CSVWriter(new FileWriter(csv));
//loop through some desired content
for (String s : content) {
//writes the string and separates by a comma (spreadsheet format)
writer.writeNext(s);
}
//close the writer
writer.close();
} catch(Exception e) {
e.printStackTrace();
}
} //end
然后将您的文件设为:
stylesheets/bootstrap.css