vuhung3990
3/24/2015 - 2:46 AM

File write, read, delete example ,must have READ, WRITE permissions

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;
    }