无聊的时候写的一个程序,发现有个问题我不理解!麻烦大家指点一下!或许还有其他地方错吧,希望大家帮我指出来!
先谢谢了!
import java.nio.ByteBuffer;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.nio.channels.FileChannel;
public class ByteBufferWrapTest{
public static void main(String[] args){
StreamTokenizerDemo tokenizer = new StreamTokenizerDemo('#');
String str = null;
String dirname = null;//如果在这里让其指向要保存的目录;
String filename = null;//这里指向要保存的文件,就可以执行!
System.out.print("请输入你要写入文件的内容:(以#结束)");
str = tokenizer.readString();
while(true){
System.out.print("请输入你要保存的路径(包括文件的扩展名):");//就是这里,为什么从键盘读取这个程序就不能执行!
filename = tokenizer.readString();
if(filename.indexOf(".") != -1)
break;
else System.out.println("\n输入不正确!请重新输入!\n");
}
int period = filename.lastIndexOf("/");
dirname = filename.substring(0,period);
filename = filename.substring(period);
File dir = new File(dirname);
if(!dir.exists()){
if(!dir.mkdir()){
System.out.println("不能创建目录!");
System.exit(1);
}
}else if(!dir.isDirectory()){
System.out.println("不是目录!");
System.exit(1);
}
File file = new File(dir,filename);
FileOutputStream outFile = null;
try{
outFile = new FileOutputStream(file,true);
}catch(FileNotFoundException e){
e.printStackTrace(System.err);
}
FileChannel outChannel = outFile.getChannel();
byte[] array = str.getBytes();
ByteBuffer buf = ByteBuffer.wrap(array);
try{
outChannel.write(buf);
}catch(IOException e){
e.printStackTrace(System.err);
System.exit(1);
}
}
}
//下面是读取键盘操作的类:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
import java.io.IOException;
public class StreamTokenizerDemo{
private StreamTokenizer tokenizer = new StreamTokenizer(
new BufferedReader(
new InputStreamReader(System.in)));
private int type;
private char separator = ',';
public StreamTokenizerDemo(char separator){
this.separator = separator;
setStreamTokenizer();
}
public void setStreamTokenizer(){
tokenizer.resetSyntax();
tokenizer.wordChars('\u0000',(char)(separator - 1));
tokenizer.wordChars((char)(separator + 1),'\u00ff');
tokenizer.whitespaceChars(separator,separator);
//tokenizer.eolIsSignificant(true);//这个好象没有也无所谓吧!?
}
public String readString(){
String str = null;
try{
if((type = tokenizer.nextToken()) == StreamTokenizer.TT_WORD)
str = tokenizer.sval;
}catch(IOException e){
e.printStackTrace(System.err);
System.exit(1);
}
return str;
}
}
[此贴子已经被作者于2006-6-28 12:03:17编辑过]