>  기사  >  Java  >  Java에서 파일을 작성하는 여러 가지 방법 공유

Java에서 파일을 작성하는 여러 가지 방법 공유

高洛峰
高洛峰원래의
2017-01-24 14:09:421280검색

1, FileWritter는 파일을 파일에 씁니다.

FileWritter, 문자 스트림은 파일에 문자를 씁니다. 기본적으로 모든 기존 콘텐츠를 새 콘텐츠로 바꾸지만 true(부울) 값이 FileWritter 생성자의 두 번째 매개 변수로 지정되면 기존 콘텐츠를 유지하고 파일 끝에 새 콘텐츠를 추가합니다.

1. 기존 콘텐츠를 모두 새 콘텐츠로 교체합니다.

new FileWriter(file);2. 기존 내용을 유지하고 새 내용을 파일 끝에 추가합니다.

new FileWriter(file,true);

추가 파일 예시
"javaio-appendfile.txt"라는 이름의 텍스트 파일이며 다음 내용을 포함합니다.

ABC Hello는 새 콘텐츠를 추가합니다 new FileWriter(file,true)

package com.yiibai.file;

import java.io.File;
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;

public class AppendToFileExample 
{
    public static void main( String[] args )
    { 
     try{
      String data = " This content will append to the end of the file";

      File file =new File("javaio-appendfile.txt");

      //if file doesnt exists, then create it
      if(!file.exists()){
       file.createNewFile();
      }

      //true = append file
      FileWriter fileWritter = new FileWriter(file.getName(),true);
             BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
             bufferWritter.write(data);
             bufferWritter.close();

         System.out.println("Done");

     }catch(IOException e){
      e.printStackTrace();
     }
    }
}

결과
이제 텍스트 파일 "javaio-appendfile.txt"의 콘텐츠는 다음과 같이 업데이트됩니다.

ABC Hello 이 내용은 파일 끝에 추가됩니다


두 번째, BufferedWriter가 파일을 씁니다

버퍼 문자(BufferedWriter)는 처리할 문자 스트림 클래스입니다. 문자 데이터. 바이트 스트림(바이트로 변환된 데이터)과 달리 문자열, 배열 또는 문자 데이터를 파일에 직접 쓸 수 있습니다.

package com.yiibai.iofile;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class WriteToFileExample {
 public static void main(String[] args) {
  try {

   String content = "This is the content to write into file";

   File file = new File("/users/mkyong/filename.txt");

   // if file doesnt exists, then create it
   if (!file.exists()) {
    file.createNewFile();
   }

   FileWriter fw = new FileWriter(file.getAbsoluteFile());
   BufferedWriter bw = new BufferedWriter(fw);
   bw.write(content);
   bw.close();

   System.out.println("Done");

  } catch (IOException e) {
   e.printStackTrace();
  }
 }
}

셋, FileOutputStream은 파일에 씁니다.


파일 출력 스트림은 원시 바이너리 데이터를 처리하는 데 사용되는 바이트 스트림 클래스입니다. 데이터를 파일에 쓰려면 데이터를 바이트로 변환하여 파일에 저장해야 합니다. 아래의 전체 예를 참조하세요.

package com.yiibai.io;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class WriteFileExample {
 public static void main(String[] args) {

  FileOutputStream fop = null;
  File file;
  String content = "This is the text content";

  try {

   file = new File("c:/newfile.txt");
   fop = new FileOutputStream(file);

   // if file doesnt exists, then create it
   if (!file.exists()) {
    file.createNewFile();
   }

   // get the content in bytes
   byte[] contentInBytes = content.getBytes();

   fop.write(contentInBytes);
   fop.flush();
   fop.close();

   System.out.println("Done");

  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   try {
    if (fop != null) {
     fop.close();
    }
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
 }
}
//更新的JDK7例如,使用新的“尝试资源关闭”的方法来轻松处理文件。
package com.yiibai.io;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class WriteFileExample {
 public static void main(String[] args) {

  File file = new File("c:/newfile.txt");
  String content = "This is the text content";

  try (FileOutputStream fop = new FileOutputStream(file)) {

   // if file doesn't exists, then create it
   if (!file.exists()) {
    file.createNewFile();
   }

   // get the content in bytes
   byte[] contentInBytes = content.getBytes();

   fop.write(contentInBytes);
   fop.flush();
   fop.close();

   System.out.println("Done");

  } catch (IOException e) {
   e.printStackTrace();
  }
 }
}

파일을 작성하고 관련 기사를 공유하는 더 많은 Java 방법을 보려면 PHP 중국어 웹사이트에 주목하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.