gpt4 book ai didi

android - 如何检查android中是否存在txt文件

转载 作者:行者123 更新时间:2023-11-29 17:31:22 25 4
gpt4 key购买 nike

我想要的是一段检查文本文件是否存在的代码。我正在使用 Java。

我想要的是这样的:

if (the file.txt exists)  { do a action } else {do another action }

该文件位于应用程序数据文件夹中的文件目录中。谢谢! :P

编辑:我这样保存文件:

public class crear_data_mes {
String nArchivo_mes = "mes.txt";
Context ctx_mes;
FileOutputStream fos_mes;
FileInputStream fis_mes;
public crear_data_mes(Context ctx) {
this.ctx_mes=ctx;
}
public void escribir_mes(String textoarchivo_mes) {
try {
fos_mes= ctx_mes.openFileOutput(nArchivo_mes, Context.MODE_PRIVATE);
fos_mes.write(textoarchivo_mes.getBytes());
fos_mes.close();
} catch (FileNotFoundException e) {
Log.e("Hola", "Hola" + e.getMessage());
} catch (IOException ex) {
Log.e("Hola", "Hola"+ex.getMessage());
}
}

public String leer_mes () {
String lectura_mes = "";
try {

fis_mes = ctx_mes.openFileInput(nArchivo_mes);
int i;
int n_mes = 0;
char caracter_mes='a';
do {
i = fis_mes.read();
if (i!='\n') {
caracter_mes = (char)i;
lectura_mes=lectura_mes+caracter_mes;
}
} while (i>0);
lectura_mes+="\n";
} catch (Exception e) { }
return lectura_mes;
}
}

最佳答案

文件exists()方法,它可以满足您的需求。

File file = new File(fileDirectory, "file.txt");
if (file.exists()) {

}

其中 fileDirectory 是您存储文件的目录。

编辑:

在您的情况下,您可以使用 getFileStreamPath ,它返回文件系统上的绝对路径,其中存储了使用 openFileOutput(String, int) 创建的文件。

例如

File file = getFileStreamPath("file.txt");
if (file.exists()) {

}

关于android - 如何检查android中是否存在txt文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32805833/

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