Java开发网 Java开发网
注册 | 登录 | 帮助 | 搜索 | 排行榜 | 发帖统计  

您没有登录

» Java开发网 » Java SE 综合讨论区  

按打印兼容模式打印这个话题 打印话题    把这个话题寄给朋友 寄给朋友    该主题的所有更新都将Email到你的邮箱 订阅主题
flat modethreaded modego to previous topicgo to next topicgo to back
作者 【求助】如何向指定文件写入字符串内容
applelfish





发贴: 14
积分: 0
于 2004-12-20 21:17 user profilesend a private message to usersearch all posts byselect and copy to clipboard. 
ie only, sorry for netscape users:-)add this post to my favorite list
我写了一个小程序,功能是在指定的D:/javacodes目录下生成一个test.java文件,具体代码如下:
import java.io.*;
import java.nio.channels.FileChannel;
import java.nio.*;

public class WriteStringToFile {
public static void main(String args[]){

String dirname ="D:/javacodes"; //文件生成的目录是D:/javacodes
String filename ="test.java"; //文件的名称是test.java
String phrase = new String("My first file for test!\n Welcome!"); //写入文件的内容
File dir = new File(dirname);

//Now check out the directory
if (!dir.exists()){ //If directory does not exist?
if (!dir.mkdir()){ //……create it?
System.out.println("Cannot create directory:"+dirname);
System.exit(1);
}
}else if(!dir.isDirectory()){
System.err.println(dirname+"is not a directory");
System.exit(1);
}

//Create the filestream????
File aFile = new File(dir,filename);
FileOutputStream outputFile=null;//Place to store the stream reference
try{
outputFile= new FileOutputStream(aFile,true);
}catch (FileNotFoundException e){
e.printStackTrace(System.err);
}

//Create the file output stream channel
FileChannel outChannel= outputFile.getChannel();

ByteBuffer buf = ByteBuffer.allocate(1024);

//Load the data into the buffer
for(int i=0;i<phrase.length();i++){
buf.putChar(phrase.charAt(i));
}

buf.flip(); //Flip the buffer ready for file write

//Write the file
try{
outChannel.write(buf);//Wtite the buffer to the file channel
outChannel.close();//Close the output stream&the channel
}catch(IOException e){
e.printStackTrace(System.err);
}
//ourgetmanualact.dialog1.disable();
}
}

运行后,确实能在D:/javacodes目录下生成一个test.java文件,我原来预期的效果是test.java文件的内容如下:
My first file for test!
Welcome!
但是结果却是一堆类似二进制数的东西,哪位高手能指点迷津啊,不胜感激!!!


littledeer1974 edited on 2004-12-20 21:32


话题树型展开
人气 标题 作者 字数 发贴时间
5964 【求助】如何向指定文件写入字符串内容 applelfish 1884 2004-12-20 21:17
4304 Re:【求助】如何向指定文件写入字符串内容 applelfish 282 2004-12-21 18:51
4321 Re:【求助】如何向指定文件写入字符串内容 naive_1010 7 2004-12-28 11:24

flat modethreaded modego to previous topicgo to next topicgo to back
  已读帖子
  新的帖子
  被删除的帖子
Jump to the top of page

   Powered by Jute Powerful Forum® Version Jute 1.5.6 Ent
Copyright © 2002-2021 Cjsdn Team. All Righits Reserved. 闽ICP备05005120号-1
客服电话 18559299278    客服信箱 714923@qq.com    客服QQ 714923