-
-
Save ar-android/29666ed17487f12ce7ba86eb6be6e438 to your computer and use it in GitHub Desktop.
File write, read, delete example
,must have READ, WRITE permissions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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