提供三个写入文本文件的函数。
public static boolean writeStringToTextFile(String content, String filePath, Charset charset)
1 public static boolean writeStringToTextFile(String content, String filePath, Charset charset){ 2 Path file = Paths.get(filePath); 3 try { 4 Files.writeString(file, content, charset); 5 return true; 6 }catch (IOException err){ 7 err.printStackTrace(); 8 return false; 9 } 10 }
public static boolean writeStringListToTextFile(List<String> lines, String filePath, Charset charset)
1 // 写入时会在每个字符串后自动添加换行符。 2 public static boolean writeStringListToTextFile(List<String> lines, String filePath, Charset charset){ 3 Path file = Paths.get(filePath); 4 try { 5 Files.write(file, lines, charset); 6 return true; 7 }catch (IOException err){ 8 err.printStackTrace(); 9 return false; 10 } 11 }
public static boolean writeStringStreamToTextFile(Stream<String> lines, String filePath, Charset charset)
1 // 写入时在每个字符串后添加换行符。 2 public static boolean writeStringStreamToTextFile(Stream<String> lines, String filePath, Charset charset){ 3 Path file = Paths.get(filePath); 4 try { 5 BufferedWriter bwriter = Files.newBufferedWriter(file, charset); 6 lines.forEach(line->{ 7 try { 8 bwriter.write(line); 9 bwriter.newLine(); 10 }catch (IOException err){ 11 err.printStackTrace(); 12 } 13 }); 14 bwriter.close(); 15 return true; 16 }catch (IOException err){ 17 err.printStackTrace(); 18 return false; 19 } 20 }
测试代码
1 public static void main(String[] args) { 2 String file = "d:/mytest.txt"; 3 String s = """ 4 窗前明月光; 5 疑是地上霜。 6 举头望明月; 7 低头思故乡。 8 """; 9 writeStringToTextFile(s, file, StandardCharsets.UTF_8); 10 List<String> dataList = List.of( 11 "窗前明月光;", 12 "疑是地上霜。", 13 "举头望明月;", 14 "低头思故乡。" 15 ); 16 writeStringListToTextFile(dataList, file, StandardCharsets.UTF_8); 17 writeStringStreamToTextFile(dataList.stream(), file, StandardCharsets.UTF_8); 18 }
标签:String,err,filePath,charset,写入,003,文本文件,static,file From: https://www.cnblogs.com/java369/p/16990869.html