java中文件操作大全

欢迎进入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();}

该方法可以设定使用何种编码,有效解决中文问题。

[1][2][3]

接受失败更是一种智者的宣言和呐喊

java中文件操作大全

相关文章:

你感兴趣的文章:

标签云:

亚洲高清电影在线, 免费高清电影, 八戒影院夜间, 八戒电影最新大片, 出轨在线电影, 午夜电影院, 在线影院a1166, 在线电影院, 在线观看美剧下载, 日本爱情电影, 日韩高清电影在线, 电影天堂网, 直播盒子app, 聚合直播, 高清美剧, 高清美剧在线观看 EhViewer-E站, E站, E站绿色版, qqmulu.com, qq目录网, qq网站目录,