C++/JAVA读写文件

---恢复内容开始---

ofstream:写文件的类

ifstream:读文件的类

// basic file operations
#include <iostream>
#include <fstream>
using namespace std;

int main () {
  ofstream myfile;
  myfile.open ("example.txt");//make the "example.txt" be associated with the  object "myfile" of the ofstream class
  myfile << "Writing this to a file.\n";//this operation of the "myfile" is applied to the "example.txt" 
  myfile.close();//this operation can notify the operating system that the file  can be availiable to be opened by other processes .Moreover,the "myfile" can be re-used to open another file then
  return 0;
}

用  is_open()判断是否成功打开文件 eg:

// reading a text file
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main () {
  string line;
  ifstream myfile ("example.txt");
  if (myfile.is_open())
  {
    while ( getline (myfile,line) )
    {
      cout << line << '\n';
    }
    myfile.close();
  }

  else cout << "Unable to open file"; 

  return 0;
}

 Java读写文件

import  java.io.*;
public class JavaIO {
    public static void main(String arg[]) throws IOException{
        FileOutputStream fos=new FileOutputStream("C:/aaa.txt");
        //向文件中写字符串
        OutputStreamWriter writer=new OutputStreamWriter(fos, "GBK");//这个使用了啥设计模式
        
        writer.append("这是我测试的字符串");
        writer.close();
        fos.close();
        //从文件中读字符串
        FileInputStream fis=new FileInputStream("C:/aaa.txt");
        InputStreamReader reader =new InputStreamReader(fis);
        StringBuffer sb=new StringBuffer();
        while(reader.ready()){
            sb.append((char)reader.read());//JAVA中,char占2字节,16位。可在存放汉字
        }
        reader.close();
        fis.close();
        
        //sb.toString();
        System.out.println(sb);
        
    }

}

 

 

---恢复内容结束---

转载于:https://www.cnblogs.com/cai-cai777/p/9429729.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值