Skip to content

Instantly share code, notes, and snippets.

@ar-android
Forked from vuhung3990/update.java
Created February 13, 2017 08:52
Show Gist options
  • Save ar-android/29666ed17487f12ce7ba86eb6be6e438 to your computer and use it in GitHub Desktop.
Save ar-android/29666ed17487f12ce7ba86eb6be6e438 to your computer and use it in GitHub Desktop.
File write, read, delete example ,must have READ, WRITE permissions
/**
* Write content into file
*
* @param path require WRITE_EXTERNAL
* @param contentString
*/
public static void writeContentFile(String path, String contentString) {
File file = new File(path);
if (!file.exists())
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
try {
FileOutputStream fos = new FileOutputStream(file);
fos.write(contentString.getBytes());
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* get content string from file
*
* @param path require READ_EXTERNAL
* @return String content of file
*/
public static String getContentFromFile(String path) {
String result = null;
File file = new File(path);
if (file.exists()) {
try {
FileInputStream fis = new FileInputStream(file);
BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
reader.close();
fis.close();
result = sb.toString();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment