IT이야기

파일을 만들고 쓰려면 어떻게 해야 하는가?

cyworld 2022. 5. 4. 21:44
반응형

파일을 만들고 쓰려면 어떻게 해야 하는가?

Java에서 (텍스트) 파일을 만들고 파일에 쓰는 가장 간단한 방법은 무엇인가?

아래의 각 코드 샘플은 다음과 같은 결과를 초래할 수 있다는 점에 유의하십시오.IOException간결성을 위해 try/catch/final block이 생략되었다.예외 처리에 대한 자세한 내용은 이 자습서를 참조하십시오.

아래의 각 코드 샘플이 이미 존재하는 경우 파일을 덮어쓰게 된다는 점에 유의하십시오.

텍스트 파일 만들기:

PrintWriter writer = new PrintWriter("the-file-name.txt", "UTF-8");
writer.println("The first line");
writer.println("The second line");
writer.close();

이진 파일 만들기:

byte data[] = ...
FileOutputStream out = new FileOutputStream("the-file-name");
out.write(data);
out.close();

Java 7 이상 사용자는 클래스를 사용하여 파일에 쓸 수 있다.

텍스트 파일 만들기:

List<String> lines = Arrays.asList("The first line", "The second line");
Path file = Paths.get("the-file-name.txt");
Files.write(file, lines, StandardCharsets.UTF_8);
//Files.write(file, lines, StandardCharsets.UTF_8, StandardOpenOption.APPEND);

이진 파일 만들기:

byte data[] = ...
Path file = Paths.get("the-file-name");
Files.write(file, data);
//Files.write(file, data, StandardOpenOption.APPEND);

Java 7 이상:

try (Writer writer = new BufferedWriter(new OutputStreamWriter(
              new FileOutputStream("filename.txt"), "utf-8"))) {
   writer.write("something");
}

그러나 이를 위한 유용한 유틸리티가 있다.

또한 a를 사용할 수 있다는 점을 참고하십시오.FileWriter그러나 기본 인코딩을 사용하는 경우가 많은데 이는 종종 좋지 않은 생각이다. 인코딩을 명시적으로 지정하는 것이 가장 좋다.

아래는 Java 7 이전의 원래의 대답이다.


Writer writer = null;

try {
    writer = new BufferedWriter(new OutputStreamWriter(
          new FileOutputStream("filename.txt"), "utf-8"));
    writer.write("Something");
} catch (IOException ex) {
    // Report
} finally {
   try {writer.close();} catch (Exception ex) {/*ignore*/}
}

파일 읽기, 쓰기 및 만들기(NIO2 포함)를 참조하십시오.

파일에 쓰고 싶은 콘텐츠가 이미 있는 경우(즉시 생성되지 않은 경우), 네이티브 I/O의 일부로 Java 7에 추가하면 목표를 달성할 수 있는 가장 간단하고 효율적인 방법을 제공한다.

기본적으로 파일을 만들고 파일에 쓰는 것은 한 줄에 불과하며, 더욱이 하나의 간단한 메서드 호출이다!

다음 예제는 6개의 서로 다른 파일을 생성하고 쓰면서 이 파일을 어떻게 사용할 수 있는지 보여 준다.

Charset utf8 = StandardCharsets.UTF_8;
List<String> lines = Arrays.asList("1st line", "2nd line");
byte[] data = {1, 2, 3, 4, 5};

try {
    Files.write(Paths.get("file1.bin"), data);
    Files.write(Paths.get("file2.bin"), data,
            StandardOpenOption.CREATE, StandardOpenOption.APPEND);
    Files.write(Paths.get("file3.txt"), "content".getBytes());
    Files.write(Paths.get("file4.txt"), "content".getBytes(utf8));
    Files.write(Paths.get("file5.txt"), lines, utf8);
    Files.write(Paths.get("file6.txt"), lines, utf8,
            StandardOpenOption.CREATE, StandardOpenOption.APPEND);
} catch (IOException e) {
    e.printStackTrace();
}
public class Program {
    public static void main(String[] args) {
        String text = "Hello world";
        BufferedWriter output = null;
        try {
            File file = new File("example.txt");
            output = new BufferedWriter(new FileWriter(file));
            output.write(text);
        } catch ( IOException e ) {
            e.printStackTrace();
        } finally {
          if ( output != null ) {
            output.close();
          }
        }
    }
}

Java에서 파일을 만들고 파일에 쓰는 매우 간단한 방법:

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

public class CreateFiles {

    public static void main(String[] args) {
        try{
            // Create new file
            String content = "This is the content to write into create file";
            String path="D:\\a\\hi.txt";
            File file = new File(path);

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

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

            // Write in file
            bw.write(content);

            // Close connection
            bw.close();
        }
        catch(Exception e){
            System.out.println(e);
        }
    }
}

여기 파일을 만들거나 덮어쓸 수 있는 작은 예제 프로그램이 있다.긴 버전이라 좀 더 쉽게 이해할 수 있어.

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;

public class writer {
    public void writing() {
        try {
            //Whatever the file path is.
            File statText = new File("E:/Java/Reference/bin/images/statsTest.txt");
            FileOutputStream is = new FileOutputStream(statText);
            OutputStreamWriter osw = new OutputStreamWriter(is);    
            Writer w = new BufferedWriter(osw);
            w.write("POTATO!!!");
            w.close();
        } catch (IOException e) {
            System.err.println("Problem writing to the file statsTest.txt");
        }
    }

    public static void main(String[]args) {
        writer write = new writer();
        write.writing();
    }
}

사용:

try (Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("myFile.txt"), StandardCharsets.UTF_8))) {
    writer.write("text to write");
} 
catch (IOException ex) {
    // Handle me
}  

사용.try()스트림을 자동으로 닫는다.이 버전은 짧고 빠르며(버퍼링됨) 인코딩을 선택할 수 있다.

이 기능은 자바 7에서 도입되었다.

텍스트 파일에 문자열을 입력하십시오.

String content = "This is the content to write into a file";
File file = new File("filename.txt");
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close(); // Be sure to close BufferedWriter

우리는 쉽게 새로운 파일을 만들고 거기에 콘텐츠를 추가할 수 있다.

저자가 EoL'd(Sun과 IBM 둘 다에 의해, 기술적으로 가장 널리 보급된 JVM)인 자바 버전에 대해 솔루션을 필요로 하는지를 명시하지 않았기 때문에, 그리고 대부분의 사람들이 텍스트(비이진) 파일이라는 것이 특정되기 전에 저자의 질문에 대답한 것 같아, 나는 내 것을 제공하기로 결정했다.대답하다


우선 자바 6은 일반적으로 수명이 다했고, 저자가 레거시 호환성이 필요하다고 명시하지 않았기 때문에 자동적으로 자바 7 이상을 의미한다고 추측한다(자바 7은 아직 IBM의 EoL'd가 아니다).파일 I/O 튜토리얼 https://docs.oracle.com/javase/tutorial/essential/io/legacy.html에서 바로 확인 가능

Java SE 7 릴리스 이전에 java.io.파일 클래스는 파일 I/O에 사용되는 메커니즘이었지만 여러 가지 단점이 있었다.

  • 많은 방법들이 실패했을 때 예외를 두지 않았기 때문에 유용한 오류 메시지를 얻는 것은 불가능했다.예를 들어 파일 삭제에 실패하면 프로그램은 "삭제 실패"를 받지만 파일이 존재하지 않아서인지, 사용자에게 권한이 없어서인지, 아니면 다른 문제가 있어서인지 알 수 없게 된다.
  • 이름 바꾸기 방법은 플랫폼 간에 일관적으로 작동하지 않았다.
  • 상징적인 연결고리에 대한 실질적인 지원은 없었다.
  • 파일 권한, 파일 소유자 및 기타 보안 속성과 같은 메타데이터에 대한 지원이 더 필요했다.파일 메타데이터에 액세스하는 것은 비효율적이었다.
  • 많은 파일 방법이 확장되지 않았다.서버 위에 대형 디렉토리 목록을 요청하는 것은 중단될 수 있다.또한 대형 디렉토리는 메모리 리소스 문제를 야기하여 서비스 거부를 초래할 수 있다.
  • 파일 트리를 재귀적으로 걸어다니고 순환 심볼 링크가 있으면 적절하게 대응할 수 있는 신뢰할 수 있는 코드를 작성할 수 없었다.

오, 그건 java.io을 제외한다.파일. 파일을 쓰거나 추가할 수 없는 경우 그 이유조차 알 수 없을 수 있다.


튜토리얼을 계속 볼 수 있다: https://docs.oracle.com/javase/tutorial/essential/io/file.html#common

텍스트 파일에 미리 작성(삭제)할 모든 행이 있는 경우, https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#write-java.nio.file.Path-java.lang.Iterable-java.nio.charset.Charset-java.nio.file.OpenOption...-

예를 들어(간단히 설명)

Path file = ...;
List<String> linesInMemory = ...;
Files.write(file, linesInMemory, StandardCharsets.UTF_8);

다른 예(부록):

Path file = ...;
List<String> linesInMemory = ...;
Files.write(file, linesInMemory, Charset.forName("desired charset"), StandardOpenOption.CREATE, StandardOpenOption.APPEND, StandardOpenOption.WRITE);

파일 내용을 원하는 대로 작성하려면: https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#newBufferedWriter-java.nio.file.Path-java.nio.charset.Charset-java.nio.file.OpenOption...-

단순화된 예(Java 8 이상):

Path file = ...;
try (BufferedWriter writer = Files.newBufferedWriter(file)) {
    writer.append("Zero header: ").append('0').write("\r\n");
    [...]
}

다른 예(부록):

Path file = ...;
try (BufferedWriter writer = Files.newBufferedWriter(file, Charset.forName("desired charset"), StandardOpenOption.CREATE, StandardOpenOption.APPEND, StandardOpenOption.WRITE)) {
    writer.write("----------");
    [...]
}

이러한 방법은 저자의 입장에서 최소한의 노력이 필요하며 [텍스트] 파일에 쓸 때 다른 모든 사람보다 선호되어야 한다.

비교적 통증이 없는 경험을 하고 싶다면 Apache Commons IO 패키지, 좀 더 구체적으로 클래스를 살펴보십시오.

타사 라이브러리를 확인하는 것을 잊지 마십시오.날짜 조작을 위한 Joda-Time, 공통 문자열 조작을 위한 Apache Commons Lang 등을 사용하면 코드를 더 쉽게 읽을 수 있다.

자바는 훌륭한 언어지만, 표준 도서관은 때때로 약간 수준이 낮다.강력하지만, 그럼에도 불구하고 낮은 수준이야.

다음은 Java에서 파일을 만들고 쓰는 몇 가지 가능한 방법들이다.

FileOutputStream 사용

try {
  File fout = new File("myOutFile.txt");
  FileOutputStream fos = new FileOutputStream(fout);
  BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
  bw.write("Write somthing to the file ...");
  bw.newLine();
  bw.close();
} catch (FileNotFoundException e){
  // File was not found
  e.printStackTrace();
} catch (IOException e) {
  // Problem when writing to the file
  e.printStackTrace();
}

FileWriter 사용

try {
  FileWriter fw = new FileWriter("myOutFile.txt");
  fw.write("Example of content");
  fw.close();
} catch (FileNotFoundException e) {
  // File not found
  e.printStackTrace();
} catch (IOException e) {
  // Error when writing to the file
  e.printStackTrace();
}

PrintWriter 사용

try {
  PrintWriter pw = new PrintWriter("myOutFile.txt");
  pw.write("Example of content");
  pw.close();
} catch (FileNotFoundException e) {
  // File not found
  e.printStackTrace();
} catch (IOException e) {
  // Error when writing to the file
  e.printStackTrace();
}

OutputStreamWriter 사용

try {
  File fout = new File("myOutFile.txt");
  FileOutputStream fos = new FileOutputStream(fout);
  OutputStreamWriter osw = new OutputStreamWriter(fos);
  osw.write("Soe content ...");
  osw.close();
} catch (FileNotFoundException e) {
  // File not found
  e.printStackTrace();
} catch (IOException e) {
  // Error when writing to the file
  e.printStackTrace();
}

자세한 내용은 Java 에서 파일을 읽고 쓰는 방법에 대한 이 튜토리얼을 참조하십시오.

어떤 이유로 작성과 작성의 행위를 분리하고자 한다면, Java는 다음과 같다.touch이다

try {
   //create a file named "testfile.txt" in the current working directory
   File myFile = new File("testfile.txt");
   if ( myFile.createNewFile() ) {
      System.out.println("Success!");
   } else {
      System.out.println("Failure!");
   }
} catch ( IOException ioe ) { ioe.printStackTrace(); }

createNewFile()존재 확인과 파일이 원자적으로 생성된다.예를 들어, 쓰기 전에 파일의 작성자임을 확인하고 싶을 때 유용할 수 있다.

사용:

JFileChooser c = new JFileChooser();
c.showOpenDialog(c);
File writeFile = c.getSelectedFile();
String content = "Input the data here to be written to your file";

try {
    FileWriter fw = new FileWriter(writeFile);
    BufferedWriter bw = new BufferedWriter(fw);
    bw.append(content);
    bw.append("hiiiii");
    bw.close();
    fw.close();
}
catch (Exception exc) {
   System.out.println(exc);
}

가장 좋은 방법은 Java7을 사용하는 것이다: Java 7은 새로운 유틸리티 클래스인 Files와 함께 파일 시스템을 사용하는 새로운 방법을 도입했다.파일 클래스를 사용하여 파일 및 디렉토리를 만들고, 이동, 복사, 삭제할 수 있으며, 파일을 읽고 파일에 쓰는 데도 사용할 수 있다.

public void saveDataInFile(String data) throws IOException {
    Path path = Paths.get(fileName);
    byte[] strToBytes = data.getBytes();

    Files.write(path, strToBytes);
}

FileChannel로 쓰기 대용량 파일을 처리하는 경우 FileChannel은 표준 IO보다 빠를 수 있다.FileChannel을 사용하여 파일에 문자열을 쓰는 코드:

public void saveDataInFile(String data) 
  throws IOException {
    RandomAccessFile stream = new RandomAccessFile(fileName, "rw");
    FileChannel channel = stream.getChannel();
    byte[] strBytes = data.getBytes();
    ByteBuffer buffer = ByteBuffer.allocate(strBytes.length);
    buffer.put(strBytes);
    buffer.flip();
    channel.write(buffer);
    stream.close();
    channel.close();
}

DataOutputStream으로 쓰기

public void saveDataInFile(String data) throws IOException {
    FileOutputStream fos = new FileOutputStream(fileName);
    DataOutputStream outStream = new DataOutputStream(new BufferedOutputStream(fos));
    outStream.writeUTF(data);
    outStream.close();
}

FileOutputStream으로 쓰기

이제 FileOutputStream을 사용하여 파일에 이진 데이터를 쓰는 방법을 알아보자.다음 코드는 String int 바이트를 변환하고 FileOutputStream을 사용하여 파일에 바이트를 기록한다.

public void saveDataInFile(String data) throws IOException {
    FileOutputStream outputStream = new FileOutputStream(fileName);
    byte[] strToBytes = data.getBytes();
    outputStream.write(strToBytes);

    outputStream.close();
}

PrintWriter로 쓰기 PrintWriter를 사용하여 형식화된 텍스트를 파일에 쓸 수 있음:

public void saveDataInFile() throws IOException {
    FileWriter fileWriter = new FileWriter(fileName);
    PrintWriter printWriter = new PrintWriter(fileWriter);
    printWriter.print("Some String");
    printWriter.printf("Product name is %s and its price is %d $", "iPhone", 1000);
    printWriter.close();
}

BufferedWriter로 쓰기: BufferedWriter를 사용하여 새 파일에 문자열 쓰기:

public void saveDataInFile(String data) throws IOException {
    BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));
    writer.write(data);

    writer.close();
}

기존 파일에 문자열 추가:

public void saveDataInFile(String data) throws IOException {
    BufferedWriter writer = new BufferedWriter(new FileWriter(fileName, true));
    writer.append(' ');
    writer.append(data);

    writer.close();
}

나는 이것이 가장 짧은 방법이라고 생각한다.

FileWriter fr = new FileWriter("your_file_name.txt"); // After '.' write
// your file extention (".txt" in this case)
fr.write("Things you want to write into the file"); // Warning: this will REPLACE your old file content!
fr.close();

기존 파일을 덮어쓰지 않고 파일을 만들려면:

System.out.println("Choose folder to create file");
JFileChooser c = new JFileChooser();
c.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
c.showOpenDialog(c);
c.getSelectedFile();
f = c.getSelectedFile(); // File f - global variable
String newfile = f + "\\hi.doc";//.txt or .doc or .html
File file = new File(newfile);

try {
    //System.out.println(f);
    boolean flag = file.createNewFile();

    if(flag == true) {
        JOptionPane.showMessageDialog(rootPane, "File created successfully");
    }
    else {
        JOptionPane.showMessageDialog(rootPane, "File already exists");
    }
    /* Or use exists() function as follows:
        if(file.exists() == true) {
            JOptionPane.showMessageDialog(rootPane, "File already exists");
        }
        else {
            JOptionPane.showMessageDialog(rootPane, "File created successfully");
        }
    */
}
catch(Exception e) {
    // Any exception handling method of your choice
}

Java 7+는 시도해 볼 만한 가치가 있다.

 Files.write(Paths.get("./output.txt"), "Information string herer".getBytes());

그것은 유망해 보인다...

이 답은 자바 8을 중심으로 하며, 자바 프로페셔널 시험에 필요한 모든 세부 사항을 다루려고 한다.그것은 왜 다른 접근법이 존재하는지를 설명하려고 노력한다.각각 장점이 있으며, 주어진 시나리오에서 각각이 가장 단순할 수 있다.

관련 세분류는 다음과 같다.

.
├── OutputStream
│   └── FileOutputStream
├── Writer
│   ├── OutputStreamWriter
│   │   └── FileWriter
│   ├── BufferedWriter
│   └── PrintWriter (Java 5+)
└── Files (Java 7+)

FileOutputStream

이 클래스는 원시 바이트 스트림을 쓰기 위한 것이다.모든.Writer아래의 접근방식은 명시적으로 또는 후드 아래에서 이 등급에 의존한다.

try (FileOutputStream stream = new FileOutputStream("file.txt");) {
    byte data[] = "foo".getBytes();
    stream.write(data);
} catch (IOException e) {}

Try-with Resources 이 처리된다는 점에 유의하십시오.stream.close() 냇물이 냇물이 냇물이 냇물이 이 냇물이 콸콸 흐르는 것과 stream.flush()(아래 예시 모두 이 접근법을 사용한다.)

OutputStreamWriter

이 클래스는 문자 스트림에서 바이트 스트림으로 이어지는 브리지다.포장할 수 있다.FileOutputStream및 문자열을 입력하십시오.

Charset utf8 = StandardCharsets.UTF_8;
try (OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(new File("file.txt")), utf8)) {
    writer.write("foo");
} catch (IOException e) {}

버퍼링된 작성기

이 클래스는 문자 출력 스트림에 텍스트를 쓰면서 문자를 버퍼링하여 단일 문자, 배열 및 문자열의 효율적인 쓰기를 제공한다.

그것은 포장할 수 있다.OutputStreamWriter:

try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File("file.txt"))))) {
    writer.write("foo");
    writer.newLine();  // method provided by BufferedWriter
} catch (IOException e) {}

Java 5 이전 버전에서는 대용량 파일(일반적인 시도/캐치 블록 포함)에 가장 적합한 접근 방식이었습니다.

파일 작성기

이것은 의 서브클래스다.OutputStreamWriter

boolean append = false;
try(FileWriter writer = new FileWriter("file.txt", append) ){
    writer.write("foo");
    writer.append("bar");
} catch (IOException e) {}

중요한 이점은 선택권이 있다는 것이다.append기존 파일에 추가 또는 덮어쓰기 여부를 결정하는 생성자 인수.추가/덮어쓰기 동작은 에 의해 제어되지 않는다는 점에 유의하십시오.write()그리고append()거의 같은 방식으로 작용하는 방법들

참고:

  • 버퍼링은 없지만, 큰 파일을 처리하기 위해서는 다음 중 하나로 포장할 수 있다.BufferedWriter.
  • FileWriter기본 인코딩 사용.종종 인코딩을 명시적으로 지정하는 것이 바람직하다.

PrintWriter

이 클래스는 형식화된 객체 표현을 텍스트 출력 스트림에 인쇄한다.후드 아래는 다음과 같다.BufferedWriter() 위로 접근하다new BufferedWriter(new OutputStreamWriter(new FileOutputStream(...)))).PrintWriter이 관용어를 편리한 방법으로 자바 5에 도입되었으며, 다음과 같은 추가 방법을 추가했다.printf()그리고println().

이 클래스의 메소드는 I/O 예외를 발생시키지 않는다.전화를 걸어 오류를 확인할 수 있다.checkError()PrintWriter 인스턴스의 대상은 File, OutputStream 또는 Writer일 수 있다.파일에 쓰는 예:

try (PrintWriter writer = new PrintWriter("file.txt", "UTF-8")) {
    writer.print("foo");
    writer.printf("bar %d $", "a", 1);
    writer.println("baz");
} catch (FileNotFoundException e) {
} catch (UnsupportedEncodingException e) {}

를 쓸때OutputStream또는Writer선택권이 있다.autoFlush생성자 매개 변수(기본적으로 false).이전과 달리FileWriter기존 파일을 덮어쓰게 된다.

파일.write()

자바 7은 소개되었다.Files.write()한 번의 호출로 파일을 생성하고 쓸 수 있다.

@icza의 대답은 이 방법을 어떻게 사용하는지를 보여준다.몇 가지 예:

Charset utf8 = StandardCharsets.UTF_8;
List<String> lines = Arrays.asList("foo", "bar");

try {
    Files.write(Paths.get("file.txt"), "foo".getBytes(utf8));
    Files.write(Paths.get("file2.txt"), lines, utf8);
} catch (IOException e) {}

이것은 버퍼를 포함하지 않기 때문에 대용량 파일에는 적합하지 않다.

파일.newBufferedWriter()

자바 7도 도입됐다.Files.newBufferedWriter()그래서 쉽게 구할 수 있고BufferedWriter:

Charset utf8 = StandardCharsets.UTF_8;
try (BufferedWriter writer = Files.newBufferedWriter(Paths.get("file.txt"), utf8)) {
    writer.write("foo");
} catch (IOException e) {}

이것은 와 비슷하다.PrintWriterPrintWriter의 방법이 없다는 단점과 예외를 받아들이지 않는다는 장점이 있다.

요약

┌───────────────────────────┬──────────────────────────┬─────────────┬──────────────┐
│                           │        Buffer for        │ Can specify │   Throws     │
│                           │       large files?       │  encoding?  │ IOException? │
├───────────────────────────┼──────────────────────────┼─────────────┼──────────────┤
│ OutputStreamWriter        │ Wrap with BufferedWriter │ Y           │ Y            │
│ FileWriter                │ Wrap with BufferedWriter │             │ Y            │
│ PrintWriter               │ Y                        │ Y           │              │
│ Files.write()             │                          │ Y           │ Y            │
│ Files.newBufferedWriter() │ Y                        │ Y           │ Y            │
└───────────────────────────┴──────────────────────────┴─────────────┴──────────────┘
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class FileWriterExample {
    public static void main(String [] args) {
        FileWriter fw= null;
        File file =null;
        try {
            file=new File("WriteFile.txt");
            if(!file.exists()) {
                file.createNewFile();
            }
            fw = new FileWriter(file);
            fw.write("This is an string written to a file");
            fw.flush();
            fw.close();
            System.out.println("File written Succesfully");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
package fileoperations;
import java.io.File;
import java.io.IOException;

public class SimpleFile {
    public static void main(String[] args) throws IOException {
        File file =new File("text.txt");
        file.createNewFile();
        System.out.println("File is created");
        FileWriter writer = new FileWriter(file);

        // Writes the content to the file
        writer.write("Enter the text that you want to write"); 
        writer.flush();
        writer.close();
        System.out.println("Data is entered into file");
    }
}

내가 찾을 수 있는 가장 간단한 방법:

Path sampleOutputPath = Paths.get("/tmp/testfile")
try (BufferedWriter writer = Files.newBufferedWriter(sampleOutputPath)) {
    writer.write("Hello, world!");
}

아마 1.7+에서만 효과가 있을 것이다.

Java 8에서 파일 및 경로를 사용하고 try-with 리소스 구성을 사용하십시오.

import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class WriteFile{
    public static void main(String[] args) throws IOException {
        String file = "text.txt";
        System.out.println("Writing to file: " + file);
        // Files.newBufferedWriter() uses UTF-8 encoding by default
        try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(file))) {
            writer.write("Java\n");
            writer.write("Python\n");
            writer.write("Clojure\n");
            writer.write("Scala\n");
            writer.write("JavaScript\n");
        } // the file will be automatically closed
    }
}

한 줄만!path그리고line스트링스

import java.nio.file.Files;
import java.nio.file.Paths;

Files.write(Paths.get(path), lines.getBytes());

입력 및 출력 스트림을 사용한 파일 읽기 및 쓰기:

//Coded By Anurag Goel
//Reading And Writing Files
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;


public class WriteAFile {
    public static void main(String args[]) {
        try {
            byte array [] = {'1','a','2','b','5'};
            OutputStream os = new FileOutputStream("test.txt");
            for(int x=0; x < array.length ; x++) {
                os.write( array[x] ); // Writes the bytes
            }
            os.close();

            InputStream is = new FileInputStream("test.txt");
            int size = is.available();

            for(int i=0; i< size; i++) {
                System.out.print((char)is.read() + " ");
            }
            is.close();
        } catch(IOException e) {
            System.out.print("Exception");
        }
    }
}

다음 패키지를 포함하십시오.

java.nio.file

그런 다음 이 코드를 사용하여 파일을 작성하십시오.

Path file = ...;
byte[] buf = ...;
Files.write(file, buf);

만약 우리가 Java 7 이상을 사용하고 있고 파일에 추가될 (추가되는) 컨텐츠도 알고 있다면 우리는 NIO 패키지에 newBufferedWriter 방법을 사용할 수 있다.

public static void main(String[] args) {
    Path FILE_PATH = Paths.get("C:/temp", "temp.txt");
    String text = "\n Welcome to Java 8";

    //Writing to the file temp.txt
    try (BufferedWriter writer = Files.newBufferedWriter(FILE_PATH, StandardCharsets.UTF_8, StandardOpenOption.APPEND)) {
        writer.write(text);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

몇 가지 유의할 점이 있다.

  1. charset 인코딩을 지정하는 것은 항상 좋은 습관이고, 우리가 클래스에 일정하게 있는 것을 위해서입니다.StandardCharsets.
  2. 코드는 다음을 사용한다.try-with-resource시도 후 리소스가 자동으로 닫히는 문장.

OP가 요청하지는 않았지만, 특정 키워드가 있는 행을 검색하고 싶을 때를 대비해서.confidentialJava에서 스트림 API를 사용할 수 있음:

//Reading from the file the first line which contains word "confidential"
try {
    Stream<String> lines = Files.lines(FILE_PATH);
    Optional<String> containsJava = lines.filter(l->l.contains("confidential")).findFirst();
    if(containsJava.isPresent()){
        System.out.println(containsJava.get());
    }
} catch (IOException e) {
    e.printStackTrace();
}

구글의 구아바 라이브러리를 이용하면 파일을 아주 쉽게 만들고 쓸 수 있다.

package com.zetcode.writetofileex;

import com.google.common.io.Files;
import java.io.File;
import java.io.IOException;

public class WriteToFileEx {

    public static void main(String[] args) throws IOException {

        String fileName = "fruits.txt";
        File file = new File(fileName);

        String content = "banana, orange, lemon, apple, plum";

        Files.write(content.getBytes(), file);
    }
}

예는 새로운 것을 창조한다.fruits.txt프로젝트 루트 디렉터리에 파일을 저장하십시오.

다음과 같은 간단한 방법이 있다.

File file = new File("filename.txt");
PrintWriter pw = new PrintWriter(file);

pw.write("The world I'm coming");
pw.close();

String write = "Hello World!";

FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);

fw.write(write);

fw.close();

시스템 속성을 사용하여 임시 파일을 만들 수도 있으며, 이 속성은 사용 중인 OS와 독립적일 것이다.

File file = new File(System.*getProperty*("java.io.tmpdir") +
                     System.*getProperty*("file.separator") +
                     "YourFileName.txt");

파일을 만들고 파일에 쓰는 방법에는 적어도 몇 가지가 있다.

작은 파일(1.7)

쓰기 방법 중 하나를 사용하여 바이트 또는 줄을 파일에 쓸 수 있다.

Path file = Paths.get("path-to-file");
byte[] buf = "text-to-write-to-file".getBytes();
Files.write(file, buf);

이러한 방법은 스트림 개폐 등 대부분의 작업을 처리하지만 대용량 파일을 처리하기 위한 것은 아니다.

버퍼링된 스트림 I/O를 사용하여 더 큰 파일 쓰기(1.7)

java.nio.file패키지는 버퍼에서 데이터를 이동하는 채널 I/O를 지원하며, 스트림 I/O 병목 현상을 일으킬 수 있는 일부 계층을 우회한다.

String s = "much-larger-text-to-write-to-file";
try (BufferedWriter writer = Files.newBufferedWriter(file, StandardCharsets.UTF_8)) {
    writer.write(s, 0, s.length());
}

이 접근방식은 특히 많은 양의 쓰기 작업을 완료할 때 성능이 효율적이기 때문에 선호된다.버퍼링된 운영은 모든 단일 바이트에 대해 운영 체제의 쓰기 방법을 호출할 필요가 없으므로 비용이 많이 드는 I/O 작업을 줄인다.

NIO API를 사용하여 출력 스트림(1.7)이 있는 파일을 복사(및파일 생성)

Path oldFile = Paths.get("existing-file-path");
Path newFile = Paths.get("new-file-path");
try (OutputStream os = new FileOutputStream(newFile.toFile())) {
    Files.copy(oldFile, os);
}

또한 입력 스트림에서 파일로 모든 바이트를 복사할 수 있는 추가 방법이 있다.

FileWriter(텍스트)(<1.7)

파일에 직접 쓰기(성능 저하)하며 쓰기 횟수가 적을 때만 사용해야 한다.파일에 문자 지향 데이터를 쓰는 데 사용된다.

String s= "some-text";
FileWriter fileWriter = new FileWriter("C:\\path\\to\\file\\file.txt");
fileWriter.write(fileContent);
fileWriter.close();

FileOutputStream(이진수)(<1.7)

FileOutputStream은 이미지 데이터와 같은 원시 바이트 스트림을 쓰기 위한 것이다.

byte data[] = "binary-to-write-to-file".getBytes();
FileOutputStream out = new FileOutputStream("file-name");
out.write(data);
out.close();

이 접근법으로 한 번에 1바이트를 쓰기보다는 항상 바이트 배열을 쓰는 것을 고려해야 한다.속도 상승은 10배 이상 증가할 수 있다.따라서 다음을 사용하는 것이 권장된다.write(byte[])가능한 한 언제나 방법.

참조URL: https://stackoverflow.com/questions/2885173/how-do-i-create-a-file-and-write-to-it

반응형