封装一个输入输出流,将要写入的数据写入到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()
}
}
首先创建一个新的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()
}
}