NIO实现文件流插入数据(粘贴功能)
来源:互联网 发布:内存条 知乎 编辑:程序博客网 时间:2024/05/14 15:00
package org1.NIO;import javafx.stage.Screen;import java.io.*;import java.nio.ByteBuffer;import java.nio.CharBuffer;import java.nio.MappedByteBuffer;import java.nio.channels.Channel;import java.nio.channels.FileChannel;import java.nio.charset.Charset;import java.util.Scanner;/** * Created by hadoop on 16-9-28.简单实现功能如下,不知道有没有不这么麻烦的方法 */public class PasteDemo { public static void main(String[] args) { String s ="text.txt"; int rows = 0; int cols = 0; Scanner input =new Scanner(System.in); System.out.println("请分别输入行号,列号"); rows =input.nextInt(); cols =input.nextInt(); System.out.println("请输入插入的数据:"); insert(s,rows+1,cols+1,input.next()); } private static void insert(String path, int rows, int cols,String data) { File sourceFile =new File(path); File distFile =new File("text2.txt"); FileChannel inChannel; FileChannel outChannel; try { inChannel = new FileInputStream(sourceFile).getChannel(); MappedByteBuffer mbf =inChannel.map(FileChannel.MapMode.READ_ONLY,0,sourceFile.length()); CharBuffer charBuffer = Charset.forName("utf-8").newDecoder().decode(mbf); String []context=charBuffer.toString().split("\n");//主意这里的反斜杠!!!!! System.out.println("测试分段的数据"+context[rows]);//一行 String insertLine=context[rows].substring(0,cols)+data+context[rows].substring(cols,context[rows].length()); System.out.println("测试修改的数据"+insertLine); context[rows]=insertLine; outChannel =new FileOutputStream(distFile).getChannel(); ByteBuffer byteBuffer =ByteBuffer.allocate(mbf.capacity()+data.length()*3); int contextLen =context.length; for (int i =0;i<contextLen;i++){ byteBuffer.put((context[i]+"\n").getBytes());//按行写入,加换行 } //读取channel,需要置位 byteBuffer.flip(); outChannel.write(byteBuffer); byteBuffer.clear();//写数据 System.out.println(byteBuffer); System.out.println("position: "+byteBuffer.position()+" limit:"+byteBuffer.limit()); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }}
0 0
- NIO实现文件流插入数据(粘贴功能)
- 利用Java NIO 实现文件监控功能。
- 巧用转置功能粘贴数据
- 巧用转置功能粘贴数据
- 巧用转置功能粘贴数据
- datagridview粘贴功能实现
- 实现 复制 粘贴功能
- java NIO实现的文件复制(包括文件与文件夹复制) NIO读取数据与写数据
- PHP+MySQL实现插入数据功能
- JS实现复制/粘贴功能
- JS实现复制/粘贴功能
- javascript实现复制粘贴功能
- android 复制 粘贴 功能实现
- 实现浏览器截图粘贴功能
- Android实现复制粘贴功能
- JS实现复制粘贴功能
- JS 实现复制粘贴功能
- Ajax实现xml文件数据插入数据库(三)---javabean实现数据库插入
- codeforce#375D. Lakes in Berland
- 智能小车制作过程全纪录: 四、软件平台--- Java 控制GPIO
- 球色问题
- Android 知识点收藏索引
- Error:Execution failed for task ':app:transformResourcesWithMergeJavaResForDebug'
- NIO实现文件流插入数据(粘贴功能)
- 数据结构笔记--绪论
- 【NOIP2016提高A组五校联考1】道路规划
- 【电脑维修系列】虚拟机VMware10.0 从U盘启动安装系统 方法
- 安装Linux系统
- listview当条目中有按钮的点击事件
- Nodejs学习笔记(十)--- 与MongoDB的交互(mongodb/node-mongodb-native)、MongoDB入门
- Spring KeyHolder
- hdu 5919 Sequence II (主席树,求区间不同数的个数)