package test; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; public class FileReadWriteTest { public static void main(String[] args) throws IOException { String filePath = "D:\\MyTextFileTest.txt"; new File(filePath).createNewFile(); writeFileContent_1(filePath, true, "中文字測試"); writeFileContent_1(filePath, true, "你好哈囉"); System.out.println(readFileContent_1(filePath)); System.out.println(readFileContent_2(filePath)); } /*************** Write File ***************/ public static void writeFileContent_1(String filePath, boolean isAppend, String contentToWrite) { try ( FileOutputStream fileOutputStream = new FileOutputStream(new File(filePath), isAppend); OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream, "UTF-8"); BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter); ){ bufferedWriter.write(contentToWrite); } catch (IOException e) { e.printStackTrace(); } } public static void writeFileContent_2(String filePath, boolean isAppend, String contentToWrite) { try { if (isAppend) { Files.writeString(Paths.get(filePath), contentToWrite, StandardCharsets.UTF_8, StandardOpenOption.APPEND); }else { Files.writeString(Paths.get(filePath), contentToWrite, StandardCharsets.UTF_8); } } catch (IOException e) { e.printStackTrace(); } } /*************** Read File ***************/ public static String readFileContent_1(String filePath) { StringBuffer fileContent = new StringBuffer(); try ( FileInputStream fileInputStream = new FileInputStream(new File(filePath)); InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8"); BufferedReader bufferedReader = new BufferedReader(inputStreamReader); ) { String readContent = ""; while ((readContent = bufferedReader.readLine()) != null) { fileContent.append(readContent + "\n"); } if (fileContent.length() > 0) { //remove the latest added "\n" fileContent.deleteCharAt(fileContent.length() - 1); } } catch (IOException e) { e.printStackTrace(); } return fileContent.toString(); } public static String readFileContent_2(String filePath) { String fileContent = ""; try { fileContent = Files.readString(Paths.get(filePath), StandardCharsets.UTF_8); } catch (IOException e) { e.printStackTrace(); } return fileContent; } }
參考資料:
沒有留言 :
張貼留言