2015-11-20 1 views
1
public static void main(String[] args) { 
    String string = "hello world!"; 
    File file = new File("test.txt"); 
    FileOutputStream fos = new FileOutputStream(file); 
    fos.write(string.getBytes()); 
    fos.close(); 
} 

Я действительно не знаю, что случилось. Я получаю ошибки в новом файле FileOutpuStream (файл), fos.write (...) и fos.close().Не удается создать файл в android и написать ему. Необработанное исключение java.io.FileNotFoundException

Прошу прощения за простой вопрос, поскольку я новичок в Java и Android.

+1

Почему происходит FileNotFoundException --- http://craftingjava.blogspot.com.au/2012/05/file-not-found-exception-file-not-found.html –

+1

test.txt не существует – zgc7009

ответ

0

Пожалуйста, добавьте коды для обработки IOException (не только FileNotFoundException). Либо поймать, либо бросить. Вот пример того, чтобы бросать его с помощью throws IOException (я проверил код и он работает, как ожидалось):

public static void main(String[] args) throws IOException { 
    String string = "hello world!"; 
    File file = new File("test.txt"); 
    FileOutputStream fos = new FileOutputStream(file); 
    fos.write(string.getBytes()); 
    fos.close(); 
} 
2

Для сохранения файла:

public void writeToFile(String data) { 
    try { 
     FileOutputStream fou = openFileOutput("data.txt", MODE_APPEND); 
     OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fou); 
     outputStreamWriter.write(data); 
     outputStreamWriter.close(); 
    } 
    catch (IOException e) { 
     Log.e("Exception", "File write failed: " + e.toString()); 
    } 
} 

Для загрузки файла:

public String readFromFile() { 

    String ret = ""; 

    try { 
     InputStream inputStream = openFileInput("data.txt"); 

     if (inputStream != null) { 
      InputStreamReader inputStreamReader = new InputStreamReader(inputStream); 
      BufferedReader bufferedReader = new BufferedReader(inputStreamReader); 
      String receiveString = ""; 
      StringBuilder stringBuilder = new StringBuilder(); 

      while ((receiveString = bufferedReader.readLine()) != null) { 
       stringBuilder.append(receiveString); 
      } 

      inputStream.close(); 
      ret = stringBuilder.toString(); 
     } 

    } 
    catch (FileNotFoundException e) { 
     Log.e("login activity", "File not found: " + e.toString()); 
    } catch (IOException e) { 
     Log.e("login activity", "Can not read file: " + e.toString()); 
    } 

    return ret; 
} 
Смежные вопросы