Java 将数据写入全路径下的指定文件
1 package com.freud.algorithm.other; 2 3 import java.io.File; 4 import java.io.FileOutputStream; 5 6 public class WriteData { 7 8 public static void main(String[] args) { 9 10 writeToFile("aaa"); 11 } 12 13 public static void writeToFile(String data) { 14 15 byte[] sourceByte = data.getBytes(); 16 String path = "D:/file/"; 17 String fileName = "test.txt"; 18 if (null != sourceByte) { 19 try { 20 File file = new File(path + fileName);//文件路径(路径+文件名) 21 if (!file.exists()) { //文件不存在则创建文件,先创建目录 22 File dir = new File(file.getParent()); 23 dir.mkdirs(); 24 file.createNewFile(); 25 } 26 FileOutputStream outStream = new FileOutputStream(file); //文件输出流将数据写入文件 27 outStream.write(sourceByte); 28 outStream.close(); 29 } catch (Exception e) { 30 e.printStackTrace(); 31 // do something 32 } finally { 33 // do something 34 } 35 } 36 } 37 }