java nio实例一

java nio的实例

Java代码 复制代码 收藏代码
  1. public class NewIOChannel {
  2. private String file = "";
  3. private String file2 = "";
  4. @Before
  5. public void init(){
  6. file = NewIOChannel.class.getResource("").getPath()+"\\myfile.txt";
  7. file2 = NewIOChannel.class.getResource("").getPath()+"\\myfile2.txt";
  8. System.out.println(file);
  9. }
  10. /**
  11. * outputStream channel写文件
  12. * @throws IOException
  13. */
  14. @Test
  15. public void FileTest() throws IOException{
  16. String info[] = {"wang","fwefwe","北京"};
  17. File file = new File(this.file);
  18. FileOutputStream output = null;
  19. output = new FileOutputStream(file);
  20. FileChannel fout = null;
  21. fout = output.getChannel();
  22. ByteBuffer buf = ByteBuffer.allocate(1024);
  23. for (int i = 0; i < info.length; i++) {
  24. buf.put(info[i].getBytes("UTF-8"));
  25. }
  26. buf.flip();
  27. fout.write(buf);
  28. fout.close();
  29. output.close();
  30. }
  31. @Test
  32. public void writeFile()throws IOException{
  33. File file = new File(this.file);
  34. FileInputStream input = new FileInputStream(file);
  35. FileChannel fileChannel = input.getChannel();
  36. byte data[] = new byte[(int)file.length()];
  37. // MappedByteBuffer mbb = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, file.length());
  38. // int foot = 0;
  39. // while(mbb.hasRemaining())
  40. // data[foot++] = mbb.get();
  41. ByteBuffer bufs = ByteBuffer.wrap(data);
  42. fileChannel.read(bufs);
  43. System.out.println(new String(data));
  44. fileChannel.close();
  45. }
  46. @Test
  47. public void writereadFile() throws IOException{
  48. File file = new File(this.file);
  49. File file2 = new File(this.file2);
  50. FileInputStream input = new FileInputStream(file);
  51. FileOutputStream output = new FileOutputStream(file2);
  52. FileChannel fout = output.getChannel();
  53. FileChannel fin = input.getChannel();
  54. ByteBuffer buf = ByteBuffer.allocate(1024);
  55. int temp =0;
  56. while ((temp = fin.read(buf)) != -1) {
  57. buf.flip();
  58. fout.write(buf);
  59. buf.clear();
  60. }
  61. fin.close();
  62. fout.close();
  63. }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值