Newer
Older
telopeditor / src / main / java / club / tmworks / io / TextFile.java
@gakkyoku_ojisan gakkyoku_ojisan on 19 Nov 2022 2 KB first commit
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package club.tmworks.io;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author MURAKAMI Takahiro <daianji@gmail.com>
 */
public class TextFile {

    public static String load(String path) {
        String rvalue = "";
        FileInputStream fis = null;
        try {
            File f = new File(path);
            fis = new FileInputStream(f);
            InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
            BufferedReader br = new BufferedReader(isr);
            String line;
            while ((line = br.readLine()) != null) {
                rvalue += line + "\n";
            }
        } catch (FileNotFoundException ex) {
            Logger.getLogger(TextFile.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(TextFile.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                if (fis != null) {
                    fis.close();
                }
            } catch (IOException ex) {
                Logger.getLogger(TextFile.class.getName()).log(Level.SEVERE, null, ex);
            }

        }
        return rvalue;
    }

    public static void save(String path, String data) {
        OutputStreamWriter osw = null;
        try {
            File f = new File(path);
            FileOutputStream fos = new FileOutputStream(f);
            osw = new OutputStreamWriter(fos, "UTF-8");
            BufferedWriter bw = new BufferedWriter(osw);
            bw.write(data);
            bw.flush();
        } catch (UnsupportedEncodingException | FileNotFoundException ex) {
            Logger.getLogger(TextFile.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(TextFile.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                if (osw != null) {
                    osw.close();
                }
            } catch (IOException ex) {
                Logger.getLogger(TextFile.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

    }
}