文件读写操作

java中对文件的操作很多,对于一个java新手,经常整理下自己遇到的新东西,为他人也提供一个参考,共同学习

 

按行读取:

采用BufferedReader中的readline()

 

public static void read() {
   String s = null;
   StringBuffer sb = new StringBuffer();
   File f = new File("D://dspace//log//dspace.viewcount");
   if (f.exists()) {
    System.out.println("文件存在");

    try {
     BufferedReader br = new BufferedReader(new InputStreamReader(
       new FileInputStream(f)));

     while ((s = br.readLine()) != null) {
      sb.append(s);
     }
     System.out.println(sb);
    } catch (Exception e) {
     e.printStackTrace();
    }
   }else{
    System.out.println("文件不存在!");
   }

  按字节读取:

 

 

 

写文件:

        File file=new File("D://dspace//log//dspace.viewcount");
       
        Date nowdate=new Date();
        SimpleDateFormat dataformat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String datastring=dataformat.format(nowdate)+" viewer:600/r/n";
       
        FileWriter fWriter=null;
        BufferedWriter bWriter=null;
        try
        {
            fWriter=new FileWriter(file,true);//保留当前内容  在最后添加
            bWriter=new BufferedWriter(fWriter);
            bWriter.write(datastring);
            bWriter.flush();
            bWriter.close();
            fWriter.close();
        }
        catch (Exception e)
        {
            e.printStackTrace();
            // TODO: handle exception
        }

你可能感兴趣的:(java,exception,Date,String,File,null)