文件的创建,写入,读取,复制文本或图片

public class Test {
    public static void main(String[] args) throws IOException {
            //声明地址
            String path="E:/Test01/";
            //声明要创建的文件名
            String newfile="1.txt";
            //创建一个File实例
            File file=new File(path,newfile);
            //如果E:/Test01/路径下的1.txt文件不存在,那就创建一个1.txt文件
           if (!file.exists()){
               file.createNewFile();
           }
    }
}

下面写文件的写入,文件就用上面所创建的文件,对文件的读写操作可以用

RandomAccessFile(一个类)
public class Test {
    public static void main(String[] args) throws IOException {
            //声明地址
            String path="E:/Test01/1.txt";
            //创建一个实例
            RandomAccessFile Raf=new RandomAccessFile(path,"rw");
            //定义一个字符串,在写入的时候把它转化为字符写入
            String text="大帅哥";
            Raf.write(text.getBytes());
           //获取已经存在文本长度
            int leng= (int) Raf.length();
            //在文本后面追加内容要调用seek()方法,可以把光标移动到所输入长度leng的后面
                Raf.seek(leng);
            //定义一个字符串,在写入时候把它转化为字符写入
            String text1="是我";
            Raf.write(text1.getBytes());
    }
}

读文件的读取也可以用RandomAccessFile类

public static void main(String[] args) throws IOException {
        //声明地址
        String path="E:/Test01/1.txt";
        //创建一个实例
        RandomAccessFile Raf=new RandomAccessFile(path,"rw");
       //把文本内容存放到一个byte数组当中
        byte[]  bytes=new byte[(int) Raf.length()];
        //读取文本内容
        Raf.read(bytes);
        //利用String构造器把文本内容输出
        System.out.println(new String(bytes));
}

下面来举文本或图片的复制

public class Test {
    public static void main(String[] args) throws IOException {
            //声明地址
            String path="E:/Test01/1.txt";
           //声明新的文本或图片
           String  newpath="E:/Test01/coyp_1.txt";
           //创建两个File实例
             File file=new File(path);
             File newFile=new File(newpath);
             //如果文件coyp_1.txt不存在,就创建
            if(!newFile.exists()){
                newFile.createNewFile();
                //读取旧文本的内容,先创建RandomAccessFile类,利用RandomAccessFile来读取和写入
                RandomAccessFile Raf=new RandomAccessFile(file,"rw");
                RandomAccessFile newRaf=new RandomAccessFile(newFile,"rw");
                //现在开始读取旧文本的内容,
                byte[] bytes=new byte[(int) Raf.length()];
                Raf.read(bytes);
                //把读取的内容写到新文本当中
                newRaf.write(bytes);
                


            }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值