使用Java中的File类,url为
文件的绝对地址,str为输入的
字符串内容。代码如下图所示:String str="i love china!" File txt=new File("url") if(!txt.exists()){ txt.createNewFile() } byte bytes[]=new byte[512] bytes=str.getBytes() //新加的 int b=str.length() //改 FileOutputStream fos=new FileOutputStream(txt) fos.write(bytes,0,b) fos.close()import java.io.File\x0d\x0aimport java.io.OutputStream\x0d\x0aimport java.io.FileOutputStream\x0d\x0apublic class TestFile {\x0d\x0apublic static void main(String[] args) throws Exception{\x0d\x0a//在d盘上创建一个名为testfile的文本文件\x0d\x0aFile f = new File("D:"+File.separator+"testfile.txt")\x0d\x0a//用FileOutputSteam包装文件,并设置文件可追加\x0d\x0aOutputStream out = new FileOutputStream(f,true)\x0d\x0a//字符数组\x0d\x0aString[] str = {"shanghai","beijing","guangdong","xiamen"}\x0d\x0afor(int i =0i/**
* 写文件
* @param to (File) 保存到的文件
* @param str (String) 字符串
* @param charset (String) 字符集编辑
* @param outNull (boolean) false: null值作为""处理
* @return
*/
public static boolean writeFile(File to, String str, String charset, boolean outNull){
if(to == null) return false
if(charset == null || charset.length() == 0) charset = "UTF-8"
BuffWriter bw = null
try {
insureDir(to.getParentFile())
bw = new BuffWriter(new OutputStreamWriter(new FileOutputStream(to), charset))
bw.setOutNull(outNull)
bw.append(str)
bw.flush()
bw.close()
bw = null
return true
} catch (IOException e) {
e.printStackTrace()
}finally{
try {
if(bw != null){
bw.close()
}
} catch (IOException e) {
e.printStackTrace()
}
}
return false
}