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);
        
    }

}

 

 

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

posted @ 2018-08-06 13:19  是甜甜啊  阅读(175)  评论(0编辑  收藏  举报