我是Android开发的新手,并且想知道实现以下目标的最佳方法是什么:
假设我的android应用程序中的文件夹中有一个.txt文件(例如我应用程序文件夹层次结构中的文件夹A)。我想阅读并处理这个.txt文件的每一行。
我想将一个字符串写入.txt文件,并将此文件放入现有文件夹(例如文件夹B)。另外,在开发我的应用程序时,我应该在哪里放置文件夹B?
我理解这是一个“强硬”的问题,因为它是一个两个问题。但是,我相信任何想知道其中一个答案的人都会想要另一个问题的答案。
任何帮助将不胜感激。谢谢你的时间!
答案 0 :(得分:0)
这就是我这样做的方式,它的工作正常!希望它能帮到你! :)
1
try {
FileInputStream in = new FileInputStream("pathToYourFile");
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String lineString;
while ((lineString = br.readLine()) != null) {
// the line is stored in lineString
}
} catch(Exception e) {
e.printStackTrace();
}
2
// Gets external storage directory
File root = android.os.Environment.getExternalStorageDirectory();
// File's directory
File dir = new File(root.getAbsolutePath() + File.separator + "yourFilesDirectory");
// The file
File file = new File(dir, "nameOfTheFile");
// Writes a line to file
try {
FileOutputStream outputStream = new FileOutputStream(file, true);
OutputStreamWriter writer = new OutputStreamWriter(outputStream);
writer.write("A line\n");
writer.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
在我的应用程序环境中,我将这些文件保存在外部存储目录中的文件夹中。
答案 1 :(得分:0)
这是我们在设备上备份数据库的方式
public static String backupPath = "backup"
public static String Path = "/mnt/sdcard/<your path>";
public static String databaseName = "toc_data";
public static String dbBackupIndex = "0";
public static void backupDB() {
String toPath = Path + "/" + backupPath + dbName;
toPath = toPath.substring(0, toPath.lastIndexOf(".")) + dbBackupIndex + ".db";
File from = new File(Path + dbName);
File to = new File(toPath);
try {
copyFile(from, to);
int newIndex = Integer.valueOf(dbBackupIndex) + 1;
if (newIndex >= 10) {
newIndex = 0;
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void copyFile(File src, File dst) throws IOException {
InputStream in = new FileInputStream(src);
boolean throwFNFE = true;
int errorCount = 1;
while (errorCount < 4) {
try {
OutputStream out = new FileOutputStream(dst);
Log.d("Copy File", "Copy File OS out: " + out.toString());
// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
throwFNFE = false;
break;
} catch (FileNotFoundException fnfe) {
try {
Thread.sleep(2000);
errorCount++;
} catch (InterruptedException ignore) {
ignore.printStackTrace();
}
}
}
if (throwFNFE) {
FileNotFoundException fnfe = new FileNotFoundException("Could not find SD card after 3 attempts");
throw fnfe;
}
}