Java에서 파일을 작성하는 여러 가지 방법 공유
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 중국어 웹사이트에 주목하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











Java의 클래스 로딩에는 부트 스트랩, 확장 및 응용 프로그램 클래스 로더가있는 계층 적 시스템을 사용하여 클래스로드, 링크 및 초기화 클래스가 포함됩니다. 학부모 위임 모델은 핵심 클래스가 먼저로드되어 사용자 정의 클래스 LOA에 영향을 미치도록합니다.

이 기사는 카페인 및 구아바 캐시를 사용하여 자바에서 다단계 캐싱을 구현하여 응용 프로그램 성능을 향상시키는 것에 대해 설명합니다. 구성 및 퇴거 정책 관리 Best Pra와 함께 설정, 통합 및 성능 이점을 다룹니다.

이 기사는 캐싱 및 게으른 하중과 같은 고급 기능을 사용하여 객체 관계 매핑에 JPA를 사용하는 것에 대해 설명합니다. 잠재적 인 함정을 강조하면서 성능을 최적화하기위한 설정, 엔티티 매핑 및 모범 사례를 다룹니다. [159 문자]

이 기사에서는 Java 프로젝트 관리, 구축 자동화 및 종속성 해상도에 Maven 및 Gradle을 사용하여 접근 방식과 최적화 전략을 비교합니다.

이 기사에서는 Maven 및 Gradle과 같은 도구를 사용하여 적절한 버전 및 종속성 관리로 사용자 정의 Java 라이브러리 (JAR Files)를 작성하고 사용하는 것에 대해 설명합니다.
