为什么改成原文件就被清空了(Channel)

youyouke 2018-02-11 01:46:16
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.CharBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;

public class FileChannelTest {

public static void main(String[] args) {
// TODO 自动生成的方法存根
File f=new File("src\\IOPackage\\FileChannelTest.java");
try(
//创建FileInputStream,以该文件输入流创建FileChannel
FileChannel inChannel=new FileInputStream(f).getChannel();
//以文件输出流创建FileChannel,用以控制输出
FileChannel outChannel=new FileOutputStream("a.txt").getChannel()){//如果将"a.txt"改成f,文件会被清空?
//将FileChannel里的全部数据映射成ByteBuffer
MappedByteBuffer buffer=inChannel.map(FileChannel.MapMode.READ_ONLY, 0, f.length());
//使用GBK的字符集来创建解码器
Charset charset=Charset.forName("GBK");
//直接将buffer里的数据全部输出
outChannel.write(buffer);
//再次调用buffer的clear()方法,复原limit、position的位置
buffer.clear();
//创建解码器(CharsetDecoder)对象
CharsetDecoder decoder=charset.newDecoder();
//使用解码器将ByteBuffer转换成CharBuffer
CharBuffer charBuffer=decoder.decode(buffer);
//CharBuffer的toString方法可以获取对应的字符串
System.out.println(charBuffer.toString());
}
catch(IOException ex){
ex.printStackTrace();
}
}
...全文
1005 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
youyouke 2018-03-06
  • 打赏
  • 举报
回复
请指教!!!
youyouke 2018-03-02
  • 打赏
  • 举报
回复
希望大家指点下!!!!!!!!!!
youyouke 2018-02-12
  • 打赏
  • 举报
回复
为什么不是在原文件后追加而是清空呢?
charon_ni 2018-02-12
  • 打赏
  • 举报
回复
呃呃呃,能把后面注释删了嘛
xiaovhao 2018-02-11
  • 打赏
  • 举报
回复

 FileOutputStream(File file)
Creates a file output stream to write to the file represented by
 the specified File object.
FileOutputStream(File file,
                boolean append)
Creates a file output stream to write to the file represented by
 the specified File object.
FileOutputStream(FileDescriptor fdObj)
Creates a file output stream to write to the specified file
 descriptor, which represents an existing connection to an actual
 file in the file system.
FileOutputStream(String name)
Creates a file output stream to write to the file with the
 specified name.
FileOutputStream(String name,
                boolean append)
Creates a file output stream to write to the file with the specified
 name.

有多个构造方法的

62,612

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧