首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

java nio范例一

2013-01-04 
java nio实例一java nio的实例?public class NewIOChannel {private String file private String fil

java nio实例一

java nio的实例

?

public class NewIOChannel {private String file = "";private String file2 = "";@Beforepublic void init(){file = NewIOChannel.class.getResource("").getPath()+"\\myfile.txt";file2 = NewIOChannel.class.getResource("").getPath()+"\\myfile2.txt";System.out.println(file);}/** * outputStream channel写文件 * @throws IOException */@Testpublic void FileTest() throws IOException{String info[] = {"wang","fwefwe","北京"};File file = new File(this.file);FileOutputStream output = null;output = new FileOutputStream(file);FileChannel fout = null;fout = output.getChannel();ByteBuffer buf = ByteBuffer.allocate(1024);for (int i = 0; i < info.length; i++) {buf.put(info[i].getBytes("UTF-8"));}buf.flip();fout.write(buf);fout.close();output.close();}@Testpublic void writeFile()throws IOException{File file = new File(this.file);FileInputStream input = new FileInputStream(file);FileChannel fileChannel = input.getChannel();byte data[] = new byte[(int)file.length()];//MappedByteBuffer mbb = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, file.length());//int foot = 0;//while(mbb.hasRemaining())//data[foot++] = mbb.get();ByteBuffer bufs = ByteBuffer.wrap(data);fileChannel.read(bufs);System.out.println(new String(data));fileChannel.close();}@Testpublic void writereadFile() throws IOException{File file = new File(this.file);File file2 = new File(this.file2);FileInputStream input = new FileInputStream(file);FileOutputStream output = new FileOutputStream(file2);FileChannel fout = output.getChannel();FileChannel fin = input.getChannel();ByteBuffer buf = ByteBuffer.allocate(1024);int temp =0;while ((temp = fin.read(buf)) != -1) {buf.flip();fout.write(buf);buf.clear();}fin.close();fout.close();}@Testpublic void FileLockDemo() throws IOException, InterruptedException{File file = new File(this.file);FileOutputStream output = new FileOutputStream(file,true);FileChannel fout = output.getChannel();FileLock lock = fout.tryLock();if(lock != null){System.out.println(file.getName()+"文件被锁定5秒");Thread.sleep(5000);lock.release();System.out.println(file.getName()+"文件被解锁");}fout.close();output.close();}}
?

热点排行