我想知道是否有人可以帮我解决将文件保存到自定义位置的问题。该应用程序的目的是在按下按钮时将数据存储在csv中,稍后可以从特定位置从Android手机上的内部磁盘传输到计算机(用于Excel查看和进一步操作)。代码当前将其存储到无法访问的私有应用程序文件夹中:
public void saveLogOnClick(View view) {
//Name of the file created
String FILENAME = "happy_log.csv";
//Obrain the current text in the files convert it to string and save it to .csv file
String entry = edtDate.getText().toString() + "," + edtTime.getText().toString() + "," +
happyScore.getText().toString() + "," + normalScore.getText().toString() + "," +
sadScore.getText().toString() + "\n";
//Open a file with the streamer/pointer
try {
FileOutputStream out = openFileOutput(FILENAME, Context.MODE_APPEND);
out.write(entry.getBytes());
out.close();
toastIt("Entry saved");
} catch (Exception e) {
e.printStackTrace();
}
}
编辑: 现在它适用于在公共目录下载中创建新文件夹的部分,以及自定义目录中的csv文件。但是,每次启动saveLogOnClick方法时,都不会将新信息附加到.csv,但只保存最新信息。
String FILENAME = "happy_log.csv";
//Obrain the current text in the files convert it to string and save it to .csv file
String entry = edtDate.getText().toString() + "," + edtTime.getText().toString() + "," +
happyScore.getText().toString() + "," + normalScore.getText().toString() + "," +
sadScore.getText().toString() + "\n";
//Open a file with the streamer/pointer
try {
File directoryDownload = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
File logDir = new File (directoryDownload, "Happy App Logs"); //Creates a new folder in DOWNLOAD directory
logDir.mkdirs();
File file = new File(logDir, FILENAME);
FileOutputStream out = new FileOutputStream(file);
out.write(entry.getBytes()); //Write the obtained string to csv
out.close();
toastIt("Entry saved");
} catch (Exception e) {
e.printStackTrace();
}
}
提前感谢您的帮助。
畸
答案 0 :(得分:0)
首先,在AndroidManifest.xml
中,您必须请求写入外部存储的权限(即在应用程序的沙箱之外)
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
然后你可以读/写&#34; / sdcard /&#34;,例如
String FILENAME = "/sdcard/happy_log.csv";
您的应用和PC都可以访问。
编辑:
你可以制作这样的目录
File picDirectory = new File("/sdcard/myFolder");
picDirectory.mkdirs();
EDIT2:
我不知道openFileOutput()是如何工作的,因为我从未使用它,但我会做以下事情:
File outfile = new File(getResources().getString(R.string.default_file_location)); // which is a string like "/sdcard/file.csv"
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter(outfile, true));
bw.append(matchNum + ",");
bw.flush();
bw.close();
} catch (IOException e) {
}