
FileWriter ff= null
try {
//查看C盘是否有a.txt文件来判定是否创建
File f=new File("c:\\a.txt")
ff = new FileWriter(f, true)//将字节写入文件末尾处,相当于追加信息。
} catch (IOException e) {
e.printStackTrace()
}
PrintWriter p = new PrintWriter(ff)
p.println("这里就可以写入要追加的内容了")//此处为追加内容
p.flush()
ff.try {
f.flush()
p.close()
ff.close()
} catch (IOException e) {
e.printStackTrace()
}
}
首先创建一个新的txt文件,然后new File(“txt文件路径”),封装一个输入输出流,将要写入的数据写入到txt中,刷新流,关闭流。
代码如下:
public static void main(String[] args) throws IOException{
String str = "这个项目什么时候上线"
File file//创建文件夹
FileOutputStream stream = null//new文件流
try {
file = new File("C:/Users/qisf/Desktop/Aa.txt")
stream = new FileOutputStream (file)//将文件夹放在文件流中
if (!file.exists()) {
file.createNewFile()
}
byte[] contentInBytes = str.getBytes()//转化成字节形
stream.write(contentInBytes)//写入
stream.flush()//写完之后刷新
stream.close()//关闭流
} catch (FileNotFoundException e) {
e.printStackTrace()
}
}
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)