Topic: 【求助】如何向指定文件写入字符串内容

  Print this page

1.【求助】如何向指定文件写入字符串内容 Copy to clipboard
Posted by: applelfish
Posted on: 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!
但是结果却是一堆类似二进制数的东西,哪位高手能指点迷津啊,不胜感激!!!

2.Re:【求助】如何向指定文件写入字符串内容 [Re: applelfish] Copy to clipboard
Posted by: applelfish
Posted on: 2004-12-21 18:51

晕,居然没人回复,还好我把中间那段改成下面这样就解决了:
//Create the file output stream channel
FileChannel outChannel= outputFile.getChannel();

ByteBuffer buf = ByteBuffer.allocate(phrase.length());
byte[] bytes= phrase.getBytes();

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

3.Re:【求助】如何向指定文件写入字符串内容 [Re: applelfish] Copy to clipboard
Posted by: naive_1010
Posted on: 2004-12-28 11:24

受教!!呵呵!


   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