Java에서 (텍스트) 파일 을 만들고 쓰는 가장 간단한 방법은 무엇입니까?
질문자 :Drew Johnson
아래의 각 코드 샘플은 IOException
던질 수 있습니다. 간결함을 위해 Try/catch/finally 블록이 생략되었습니다. 예외 처리에 대한 정보는 이 튜토리얼 을 참조하십시오.
아래의 각 코드 샘플은 파일이 이미 있는 경우 덮어씁니다.
텍스트 파일 만들기:
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 이상 사용자는 Files
클래스를 사용하여 파일에 쓸 수 있습니다.
텍스트 파일 만들기:
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);
Michael
자바 7 이상:
try (Writer writer = new BufferedWriter(new OutputStreamWriter( new FileOutputStream("filename.txt"), "utf-8"))) { writer.write("something"); }
하지만 다음과 같은 유용한 유틸리티가 있습니다.
- commons-io의 FileUtils.writeStringtoFile(..)
- 구아바의 Files.write(..)
참고 또한 당신이 사용할 수있는 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 포함).
Bozho
파일에 쓰고자 하는 콘텐츠(즉시 생성되지 않음)가 이미 있는 경우 java.nio.file.Files
추가하면 가장 간단하고 효율적인 방법을 얻을 수 있습니다. 당신의 목표.
기본적으로 파일을 만들고 쓰는 것은 한 줄이며, 게다가 한 번의 간단한 메서드 호출입니다 !
다음 예제에서는 사용 방법을 보여주기 위해 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(); }
icza
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(); } } } }
Eric Petroelje
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); } } }
Anuj Dhiman
다음은 파일을 생성하거나 덮어쓰는 간단한 예제 프로그램입니다. 긴 버전이므로 더 쉽게 이해할 수 있습니다.
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(); } }
Draeven
사용하다:
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()
를 사용하면 스트림이 자동으로 닫힙니다. 이 버전은 짧고 빠르며(버퍼링됨) 인코딩을 선택할 수 있습니다.
이 기능은 Java 7에서 도입되었습니다.
icl7126
다음은 텍스트 파일에 문자열을 입력하는 것입니다.
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
새 파일을 쉽게 만들고 내용을 추가할 수 있습니다.
iKing
비교적 고통 없는 경험을 원한다면 Apache Commons IO 패키지 , 보다 구체적으로 FileUtils
클래스를 살펴볼 수도 있습니다.
타사 라이브러리를 확인하는 것을 잊지 마십시오. 날짜 조작을 위한 Joda-Time , 일반적인 문자열 작업을 위한 Apache Commons Lang StringUtils
등은 코드를 더 읽기 쉽게 만들 수 있습니다.
Java는 훌륭한 언어이지만 표준 라이브러리는 때때로 약간 낮은 수준입니다. 강력하지만 그럼에도 불구하고 낮은 수준입니다.
extraneon
저자는 EoL된 Java 버전(Sun과 IBM 모두 기술적으로 가장 널리 사용되는 JVM)에 대한 솔루션이 필요한지 여부를 지정하지 않았으며 대부분의 사람들이 답변한 것으로 보이기 때문입니다. 텍스트(비바이너리) 파일이라고 명시되기 전 작성자의 질문에 답변을 드리기로 결정했습니다.
우선, Java 6은 일반적으로 수명이 다했으며 작성자가 레거시 호환성이 필요하다고 지정하지 않았기 때문에 자동으로 Java 7 이상을 의미한다고 생각합니다(Java 7은 아직 IBM에서 EoL'하지 않음). 따라서 파일 I/O 자습서를 바로 볼 수 있습니다. https://docs.oracle.com/javase/tutorial/essential/io/legacy.html
Java SE 7 릴리스 이전에는 java.io.File 클래스가 파일 I/O에 사용된 메커니즘이었지만 몇 가지 단점이 있었습니다.
- 많은 메서드가 실패했을 때 예외를 throw하지 않았으므로 유용한 오류 메시지를 얻는 것이 불가능했습니다. 예를 들어, 파일 삭제가 실패하면 프로그램은 "삭제 실패"를 수신하지만 파일이 존재하지 않았기 때문인지, 사용자에게 권한이 없었는지 또는 다른 문제가 있었는지 알 수 없습니다.
- 이름 바꾸기 방법이 여러 플랫폼에서 일관되게 작동하지 않았습니다.
- 심볼릭 링크에 대한 실질적인 지원은 없었습니다.
- 파일 권한, 파일 소유자 및 기타 보안 속성과 같은 메타데이터에 대한 더 많은 지원이 필요했습니다. 파일 메타데이터에 액세스하는 것은 비효율적이었습니다.
- 많은 File 메서드가 확장되지 않았습니다. 서버를 통해 큰 디렉토리 목록을 요청하면 중단될 수 있습니다. 큰 디렉터리는 메모리 리소스 문제를 일으켜 서비스 거부가 발생할 수도 있습니다.
- 순환 심볼릭 링크가 있는 경우 파일 트리를 재귀적으로 탐색하고 적절하게 응답할 수 있는 신뢰할 수 있는 코드를 작성하는 것은 불가능했습니다.
아, 그건 java.io.File을 배제합니다. 파일을 작성/추가할 수 없는 경우 이유조차 모를 수 있습니다.
튜토리얼을 계속 볼 수 있습니다. 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("----------"); [...] }
이러한 방법은 작성자의 노력을 최소화해야 하며 [텍스트] 파일에 쓸 때 다른 모든 방법보다 선호해야 합니다.
afk5min
다음은 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에서 파일 을 읽고 쓰는 방법에 대한 이 자습서를 추가로 확인하십시오.
Mehdi
어떤 이유로 작성과 쓰기를 분리하려는 경우 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()
은 존재 확인 및 파일 생성을 원자적으로 수행합니다. 예를 들어, 파일에 쓰기 전에 파일 작성자인지 확인하려는 경우에 유용할 수 있습니다.
Mark Peters
사용하다:
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); }
Rohit ZP
가장 좋은 방법은 Java7을 사용하는 것입니다. Java 7은 새로운 유틸리티 클래스인 Files와 함께 파일 시스템을 사용하는 새로운 방법을 소개합니다. 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(); }
sajad abbasi
나는 이것이 가장 짧은 방법이라고 생각합니다.
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();
ben
기존 파일을 덮어쓰지 않고 파일을 생성하려면:
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 }
aashima
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(); } } }
Anurag Goel
Java 7 이상에서 시도해 볼 가치가 있습니다.
Files.write(Paths.get("./output.txt"), "Information string herer".getBytes());
유망해 보입니다...
Zuko
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"); } }
Suthan Srinivasan
내가 찾을 수있는 가장 간단한 방법 :
Path sampleOutputPath = Paths.get("/tmp/testfile") try (BufferedWriter writer = Files.newBufferedWriter(sampleOutputPath)) { writer.write("Hello, world!"); }
아마도 1.7 이상에서만 작동합니다.
qed
Java 8에서는 파일 및 경로를 사용하고 자원으로 시도 구성을 사용합니다.
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 } }
praveenraj4ever
한줄만! path
와 line
은 문자열입니다.
import java.nio.file.Files; import java.nio.file.Paths; Files.write(Paths.get(path), lines.getBytes());
Ran Adler
입력 및 출력 스트림을 사용하여 파일 읽기 및 쓰기:
//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"); } } }
Anurag Goel
이 패키지를 포함하기만 하면 됩니다.
java.nio.file
그런 다음 이 코드를 사용하여 파일을 작성할 수 있습니다.
Path file = ...; byte[] buf = ...; Files.write(file, buf);
user4880283
이 답변은 Java 8을 중심으로 작성되었으며 Java Professional Exam에 필요한 모든 세부 정보를 다루려고 합니다. 다른 접근 방식이 존재하는 이유를 설명하려고 합니다. 각각의 장점이 있으며 주어진 시나리오에서 가장 간단할 수 있습니다.
관련된 수업은 다음과 같습니다.
. ├── OutputStream │ └── FileOutputStream ├── Writer │ ├── OutputStreamWriter │ │ └── FileWriter │ ├── BufferedWriter │ └── PrintWriter (Java 5+) └── Files (Java 7+)
파일출력스트림
이 클래스는 원시 바이트 스트림을 작성하기 위한 것입니다. 아래의 모든 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()
와 같이 스트림을 닫으면 이를 플러시합니다(아래의 모든 예제에서는 이 접근 방식을 사용함).
출력스트림작가
이 클래스는 문자 스트림에서 바이트 스트림으로의 다리입니다. FileOutputStream
래핑하고 문자열을 작성할 수 있습니다.
Charset utf8 = StandardCharsets.UTF_8; try (OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(new File("file.txt")), utf8)) { writer.write("foo"); } catch (IOException e) {}
BufferedWriter
이 클래스는 단일 문자, 배열 및 문자열의 효율적인 쓰기를 제공하기 위해 문자를 버퍼링하는 문자 출력 스트림에 텍스트를 씁니다.
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 이전에는 대용량 파일에 대한 최상의 접근 방식이었습니다(일반 try/catch 블록 포함).
파일라이터
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
는 기본 인코딩을 사용합니다. 인코딩을 명시적으로 지정하는 것이 더 나은 경우가 많습니다.
인쇄작가
이 클래스는 개체의 형식이 지정된 표현을 텍스트 출력 스트림에 인쇄합니다. 내부적으로는 BufferedWriter
접근 방식 new BufferedWriter(new OutputStreamWriter(new FileOutputStream(...)))
). PrintWriter
는 이 관용구를 호출하는 편리한 방법으로 Java 5에 도입되었으며 printf()
및 println()
과 같은 추가 메서드를 추가합니다.
이 클래스의 메서드는 I/O 예외를 throw하지 않습니다. 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
와 달리 기존 파일을 덮어씁니다.
Files.write()
Java 7은 java.nio.file.Files
도입했습니다. 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) {}
이것은 버퍼를 포함하지 않으므로 대용량 파일에는 적합하지 않습니다.
Files.newBufferedWriter()
Java 7은 또한 BufferedWriter
쉽게 얻을 수 있도록 하는 Files.newBufferedWriter()
를 도입했습니다.
Charset utf8 = StandardCharsets.UTF_8; try (BufferedWriter writer = Files.newBufferedWriter(Paths.get("file.txt"), utf8)) { writer.write("foo"); } catch (IOException e) {}
이 유사하다 PrintWriter
의 PrintWriter의 방법을 가지고 있지의 단점, 그리고 그 혜택과 함께, 예외를 삼키는하지 않습니다 .
요약
┌───────────────────────────┬──────────────────────────┬─────────────┬──────────────┐ │ │ 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 │ └───────────────────────────┴──────────────────────────┴─────────────┴──────────────┘
Derek Hill
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(); } }
주의할 점이 몇 가지 있습니다.
- charset 인코딩을 지정하는 것은 항상 좋은 습관이며 이를 위해
StandardCharsets
클래스에 상수가 있습니다. - 이 코드는
try-with-resource
문을 사용하여 리소스가 try 후에 자동으로 닫힙니다.
OP는 요청하지 않았지만 특정 키워드(예: confidential
가 있는 행을 검색하려는 경우를 대비하여 Java에서 스트림 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(); }
akhil_mittal
다음과 같은 몇 가지 간단한 방법이 있습니다.
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();
imvp
사용 중인 OS와 무관 한 시스템 속성을 사용하여 임시 파일을 만들 수도 있습니다.
File file = new File(System.*getProperty*("java.io.tmpdir") + System.*getProperty*("file.separator") + "YourFileName.txt");
Muhammed Sayeed
Google의 Guava 라이브러리를 사용하여 매우 쉽게 파일을 만들고 쓸 수 있습니다.
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
Jan Bodnar
JFilechooser를 사용하여 고객과 컬렉션을 읽고 파일에 저장합니다.
private void writeFile(){ JFileChooser fileChooser = new JFileChooser(this.PATH); int retValue = fileChooser.showDialog(this, "Save File"); if (retValue == JFileChooser.APPROVE_OPTION){ try (Writer fileWrite = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileChooser.getSelectedFile())))){ this.customers.forEach((c) ->{ try{ fileWrite.append(c.toString()).append("\n"); } catch (IOException ex){ ex.printStackTrace(); } }); } catch (IOException e){ e.printStackTrace(); } } }
hasskell
출처 : http:www.stackoverflow.com/questions/2885173/how-do-i-create-a-file-and-write-to-it
'etc. > StackOverFlow' 카테고리의 다른 글
Apache Camel은 정확히 무엇입니까? (0) | 2022.03.07 |
---|---|
GitHub 리포지토리에서 단일 폴더 또는 디렉터리 다운로드 (0) | 2022.03.07 |
Android 회전 시 활동 다시 시작 (0) | 2022.03.07 |
jQuery를 사용하여 JavaScript 객체에서 선택 항목에 옵션을 추가하는 가장 좋은 방법은 무엇입니까? (0) | 2022.03.07 |
데이터베이스의 모든 테이블 크기 가져오기 (0) | 2022.03.07 |