在java中如何把一个文件放到指定的文件夹中

在java中如何把一个文件放到指定的文件夹中,第1张

首先获得fileoutput对象时,写入具体的目录就可以了。

比如知虚:你要写尺乎入到d:\java\test目搭困燃录下。

方法一:

java代码

string

name

=

"out.html"

string

dir

=

"d:\\java\\test"

file

file

=

new

file(dir,name)

fileoutputstream

out

=

new

fileoutputstream(file)

方法二:

java代码

fileoutputstream

out

=

new

fileoutputstream(dir+"\\"+name)

java写入文件到指定信穗文件夹的方法主要有两种:利用PrintStream和利用StringBuffer

例如将文本“I'm the text to be write”写入到文件夹D:/test下,并命名为test.txt,则两迅衡种方式简单实现代码如下:

1. 利用PrintStream写文件

public void PrintStreamDemo(){

try {

FileOutputStream out=new FileOutputStream("D:/test.txt")

PrintStream p=new PrintStream(out)

p.println("I'm the text to be write")

} catch (FileNotFoundException e){

e.printStackTrace()

}

}

2. 利用StringBuffer写文件

public void StringBufferDemo() throws IOException{

File file=new File("D:/test.txt")

if(!file.exists())

file.createNewFile()

FileOutputStream out=new FileOutputStream(file,true)

StringBuffer sb=new StringBuffer()

sb.append("I'm the text to be write")

out.write(sb.toString().getBytes("utf-8"))

}

out.close()

}

提示:利用StringBuffer写文件可以设定使用何滑昌卜种编码,有效解决中文问题。


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/tougao/12167147.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-21
下一篇 2023-05-21

发表评论

登录后才能评论

评论列表(0条)

保存