applelfish
发贴: 14
积分: 0
|
于 2004-12-20 21:17
我写了一个小程序,功能是在指定的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
|