欢迎进入Java社区论坛,与200万技术人员互动交流 >>进入
一.获得控制台用户输入的信息
/***//**获得控制台用户输入的信息*@return*@throwsIOException*/publicStringgetInputMessage()throwsIOException…{System.out.println(“请输入您的命令∶”);bytebuffer[]=newbyte[1024];intcount=System.in.read(buffer);char[]ch=newchar[count-2];//最后两位为结束符,删去不要for(inti=0;i<count-2;i++)ch[i]=(char)buffer[i];Stringstr=newString(ch);returnstr;}
可以返回用户输入的信息,不足之处在于不支持中文输入,有待进一步改进。
二.复制文件
1.以文件流的方式复制文件
/***//**以文件流的方式复制文件*@paramsrc文件源目录*@paramdest文件目的目录*@throwsIOException*/publicvoidcopyFile(Stringsrc,Stringdest)throwsIOException…{FileInputStreamin=newFileInputStream(src);Filefile=newFile(dest);if(!file.exists())file.createNewFile();FileOutputStreamout=newFileOutputStream(file);intc;bytebuffer[]=newbyte[1024];while((c=in.read(buffer))!=-1)…{for(inti=0;i<c;i++)out.write(buffer[i]);}in.close();out.close();}
该方法经过测试,支持中文处理,并且可以复制多种类型,比如txt,xml,jpg,doc等多种格式
三.写文件
1.利用PrintStream写文件
/***//***文件输出示例*/publicvoidPrintStreamDemo()…{try…{FileOutputStreamout=newFileOutputStream(“D:/test.txt”);PrintStreamp=newPrintStream(out);for(inti=0;i<10;i++)p.println(“Thisis”+i+”line”);}catch(FileNotFoundExceptione)…{e.printStackTrace();}}
2.利用StringBuffer写文件
publicvoidStringBufferDemo()throwsIOException……{Filefile=newFile(“/root/sms.log”);if(!file.exists())file.createNewFile();FileOutputStreamout=newFileOutputStream(file,true);for(inti=0;i<10000;i++)……{StringBuffersb=newStringBuffer();sb.append(“这是第”+i+”行:前面介绍的各种方法都不关用,为什么总是奇怪的问题”);out.write(sb.toString().getBytes(“utf-8”));}out.close();}