欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java读写文件和Scala读写文件

程序员文章站 2024-03-21 19:07:34
...

Java实现

package com.xtd.test.java;

import java.io.*;

public class AppentFile {

    private static FileWriter fileWriter = null;
    private static FileReader fileReader = null;
    private static BufferedWriter bufferedWriter = null;
    private static BufferedReader bufferedReader = null;

    public static void main(String[] args) {
        String MMSIFile = "F:/IDEA-WorkSpace/spark";
        try {
            // 写文件对象
            fileWriter = new FileWriter(MMSIFile+"/MMSIFile",true);
            bufferedWriter = new BufferedWriter(fileWriter);
            bufferedWriter.write(" java appent file1\n");
            bufferedWriter.write(" java appent file2\n");
            bufferedWriter.write(" java appent file3\n");
            bufferedWriter.close();

            // 读文件对象
            fileReader = new FileReader(MMSIFile+"/MMSIFile");
            // 读文件对象
            bufferedReader = new BufferedReader(fileReader);
            String str;
            while ( null != (str = bufferedReader.readLine()) ) {
                System.out.println(str);
            }
            bufferedReader.close();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Scala实现

package com.xtd.test.scala

import java.io.{BufferedReader, BufferedWriter, FileReader, FileWriter, IOException}

object AppentFile {

  var fileWriter:FileWriter = null
  var fileReader:FileReader = null
  var bufferedWriter:BufferedWriter = null
  var bufferedReader:BufferedReader = null

  def main(args: Array[String]): Unit = {

    val MMSIFile = "F:/IDEA-WorkSpace/spark"

    try {
      // 写文件对象
      fileWriter = new FileWriter(MMSIFile + "/MMSIFile", true)
      bufferedWriter = new BufferedWriter(fileWriter)
      bufferedWriter.write("scala appent file1\n")
      bufferedWriter.write("scala appent file2\n")
      bufferedWriter.write("scala appent file3\n")
      bufferedWriter.close()

      // 读文件对象
      fileReader = new FileReader(MMSIFile + "/MMSIFile")
      bufferedReader = new BufferedReader(fileReader)
      var str:String = null
      while ( None != (str=bufferedReader.readLine()) && null != str ) {
        println(str)
      }
      bufferedReader.close()
    } catch {
      case e: IOException =>
        e.printStackTrace()
    }
  }
}

执行结果

 java appent file1
 java appent file2
 java appent file3
scala appent file1
scala appent file2
scala appent file3