0
In meiner MainActivity-Klasse in OnResume-Methode starte ich WriteFile-Methode. Die Klasse, die die Methode enthält:FileNotFoundEception in FileInputStream in Android
public class CacheFile {
private static final String TAG = "CacheFile";
private static final String mFileName="cachefile.txt";
private static File file;
//Write data into the file
public static void writeFile(Context context, String data) {
FileOutputStream outputStream=null;
String oldData=readFile(context)+"&"+data;
try {
file = new File(context.getCacheDir(), mFileName);
outputStream = new FileOutputStream(file);
if(data!=null) {
outputStream.write(oldData.getBytes());
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if(outputStream!=null){
try{
outputStream.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
}
//Read from file
public static String readFile(Context context) {
BufferedReader inputStream = null;
FileInputStream fis = null;
StringBuffer buffer = new StringBuffer();
String line;
try {
file = new File(context.getCacheDir(), mFileName);
fis=new FileInputStream(file);
inputStream = new BufferedReader(new InputStreamReader(fis));
while ((line = inputStream.readLine()) != null) {
buffer.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if(inputStream!=null){
try{
inputStream.close();
}catch (Exception e){
e.printStackTrace();
}
}
if(fis!=null){
try{
fis.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
return buffer.toString();
}
public static void deleteFile(Context context){
if(file!=null){
file.delete();
}
}
}
Die erste I readfile und fügen Sie die Informationen für das Schreiben, aber wenn ich versuche, Datei-I FileNotFoundException in Zeile erhalten zu lesen:
fis=new FileInputStream(file) (readfile method).
Warum?
Ja, danke, es funktioniert. Sollte ich die createNewFile-Methode zur writeFile-Methode hinzufügen? oder es ist genug, um in readFile-Methode hinzuzufügen. – Delphian
Wird nicht benötigt, weil in 'writeFile()' die erste aufgerufene Methode 'readFile()' ist. –
Vielen Dank für Ihre Antwort! – Delphian