Oct 22, 2013

[android] File Input and Output

If you want to write something:

File myFile = mCon.getDir("myFile", Activity.MODE_WORLD_WRITEABLE); 
String path = myFile.getAbsolutePath(); 
File file = new File(path + "/config.txt");
String strContent  = "my file save"; 

try
{
FileOutputStream fos = new FileOutputStream(file, false);
fos.write(strContent.getBytes());
fos.close();
}
catch(Exception e)
{
Log.e("klx", e.toString());
}


And how to read from file:

File myFile = mCon.getDir("myFile", Activity.MODE_WORLD_WRITEABLE); 
String path = myFile.getAbsolutePath(); 
File file = new File(path + "/config.txt");

if (file.exists() == false)  
{
    // do something
}

try 
{            
FileInputStream fis = new FileInputStream(path + "/config.txt");
BufferedReader bufferReader = new BufferedReader(new InputStreamReader(fis));
        String str = bufferReader.readLine(); 
   
Log.d("klx", "klx  " + str);  // Now you have what you want. 
   
        fis.close();  
     
}    
catch(IOException e)
{
     Log.e("klx", "e.toString());  
}

No comments:

Post a Comment