sourcecode

Java를 사용하여 문자열을 텍스트파일에 저장하려면 어떻게 해야 하나요?

copyscript 2022. 8. 7. 16:47
반응형

Java를 사용하여 문자열을 텍스트파일에 저장하려면 어떻게 해야 하나요?

Java에서는 "text"라는 문자열 변수에 텍스트 필드의 텍스트가 있습니다.

텍스트 변수의 내용을 파일에 저장하려면 어떻게 해야 합니까?

바이너리 데이터가 아닌 단순히 텍스트를 출력하는 경우 다음 기능이 작동합니다.

PrintWriter out = new PrintWriter("filename.txt");

그런 다음 출력 스트림과 마찬가지로 String을 씁니다.

out.println(text);

여전히 예외 처리가 필요합니다. .out.close()시시면됩됩됩됩됩됩

Java 7 이후를 사용하는 경우 "리소스와 함께 시도" 문을 사용하면 자동으로 닫힙니다.PrintStream으로) 다

try (PrintWriter out = new PrintWriter("filename.txt")) {
    out.println(text);
}

필요가 요.java.io.FileNotFoundException종전과 같이

Apache Commons IO에는 이를 위한 몇 가지 훌륭한 방법이 포함되어 있습니다.특히 FileUtils에는 다음과 같은 방법이 포함되어 있습니다.

static void writeStringToFile(File file, String data) 

그러면 다음 중 하나의 메서드콜로 파일에 텍스트를 쓸 수 있습니다.

FileUtils.writeStringToFile(new File("test.txt"), "Hello File");

파일의 인코딩을 지정하는 것도 고려할 수 있습니다.

Java 7에서는 다음을 수행할 수 있습니다.

String content = "Hello File!";
String path = "C:/a.txt";
Files.write( Paths.get(path), content.getBytes());

자세한 것은, http://www.drdobbs.com/jvm/java-se-7-new-file-io/231600403 를 참조해 주세요.

Java 파일 API 보기

간단한 예:

try (PrintStream out = new PrintStream(new FileOutputStream("filename.txt"))) {
    out.print(text);
}

방금 내 프로젝트에서 비슷한 일을 했어.FileWriter를 사용하면 작업의 일부가 단순해집니다.여기에 멋진 튜토리얼이 있습니다.

BufferedWriter writer = null;
try
{
    writer = new BufferedWriter( new FileWriter( yourfilename));
    writer.write( yourstring);

}
catch ( IOException e)
{
}
finally
{
    try
    {
        if ( writer != null)
        writer.close( );
    }
    catch ( IOException e)
    {
    }
}

FileUtils.writeStringToFile()Apache Commons IO에서 가져옵니다.이 바퀴를 재창조할 필요는 없습니다.

Java 11에서는java.nio.file.Files클래스는 문자열을 파일에 쓰기 위한 두 가지 새로운 유틸리티 메서드에 의해 확장되었습니다.첫 번째 방법(여기서 JavaDoc 참조)은 charset UTF-8을 기본값으로 사용합니다.

Files.writeString(Path.of("my", "path"), "My String");

두 번째 방법(여기 JavaDoc 참조)에서는 개별 문자 집합을 지정할 수 있습니다.

Files.writeString(Path.of("my", "path"), "My String", StandardCharset.ISO_8859_1);

두 방법 모두 파일 처리 옵션을 설정하기 위한 선택적 Varargs 매개 변수가 있습니다(여기 JavaDoc 참조).다음 예제에서는 존재하지 않는 파일을 만들거나 기존 파일에 문자열을 추가합니다.

Files.writeString(Path.of("my", "path"), "String to append", StandardOpenOption.CREATE, StandardOpenOption.APPEND);

아래 코드 수정을 사용하여 텍스트를 처리하는 클래스나 함수의 파일을 쓸 수 있습니다.세상에 왜 새로운 텍스트 편집기가 필요한지 궁금하네요...

import java.io.*;

public class Main {

    public static void main(String[] args) {

        try {
            String str = "SomeMoreTextIsHere";
            File newTextFile = new File("C:/thetextfile.txt");

            FileWriter fw = new FileWriter(newTextFile);
            fw.write(str);
            fw.close();

        } catch (IOException iox) {
            //do stuff with exception
            iox.printStackTrace();
        }
    }
}

저는 이런 종류의 작업을 위해 가능한 한 도서관에 의존하는 것을 선호합니다.이것은 내가 실수로 중요한 단계를 생략할 가능성이 낮아지게 한다(위의 늑대의 실수처럼).몇 가지 라이브러리는 위에서 추천하고 있습니다만, 제가 가장 좋아하는 것은 Google Guava입니다.Guava에는 이 작업에 적합한 Files라는 클래스가 있습니다.

// This is where the file goes.
File destination = new File("file.txt");
// This line isn't needed, but is really useful 
// if you're a beginner and don't know where your file is going to end up.
System.out.println(destination.getAbsolutePath());
try {
    Files.write(text, destination, Charset.forName("UTF-8"));
} catch (IOException e) {
    // Useful error handling here
}

사용.Java 7:

public static void writeToFile(String text, String targetFilePath) throws IOException
{
    Path targetPath = Paths.get(targetFilePath);
    byte[] bytes = text.getBytes(StandardCharsets.UTF_8);
    Files.write(targetPath, bytes, StandardOpenOption.CREATE);
}

Apache Commons IO api를 사용합니다.심플하다

API를 다음으로 사용

 FileUtils.writeStringToFile(new File("FileNameToWrite.txt"), "stringToWrite");

메이븐 의존 관계

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.4</version>
</dependency>

매우 읽기 쉽기 때문에, 이것을 사용해 주세요.

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

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

하나의 문자열을 기반으로 텍스트 파일을 작성해야 하는 경우:

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

public class StringWriteSample {
    public static void main(String[] args) {
        String text = "This is text to be saved in file";

        try {
            Files.write(Paths.get("my-file.txt"), text.getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
import java.io.*;

private void stringToFile( String text, String fileName )
 {
 try
 {
    File file = new File( fileName );

    // 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( text );
    bw.close( );
    //System.out.println("Done writing to " + fileName); //For testing 
 }
 catch( IOException e )
 {
 System.out.println("Error: " + e);
 e.printStackTrace( );
 }
} //End method stringToFile

이 메서드를 클래스에 삽입할 수 있습니다.기본 메서드가 포함된 클래스에서 이 메서드를 사용하는 경우 정적 키워드를 추가하여 이 클래스를 정적으로 변경합니다.어느 쪽이든, java.io 를 Import 할 필요가 있습니다.* 그렇지 않으면 File, FileWriter 및 BufferedWriter는 인식되지 않습니다.

다음과 같이 할 수 있습니다.

import java.io.*;
import java.util.*;

class WriteText
{
    public static void main(String[] args)
    {   
        try {
            String text = "Your sample content to save in a text file.";
            BufferedWriter out = new BufferedWriter(new FileWriter("sample.txt"));
            out.write(text);
            out.close();
        }
        catch (IOException e)
        {
            System.out.println("Exception ");       
        }

        return ;
    }
};

org.apache.commons.io 를 사용합니다.파일 유틸리티:

FileUtils.writeStringToFile(new File("log.txt"), "my string", Charset.defaultCharset());

한 블록의 텍스트만 파일로 푸시하는 경우 매번 덮어씁니다.

JFileChooser chooser = new JFileChooser();
int returnVal = chooser.showSaveDialog(this);
if (returnVal == JFileChooser.APPROVE_OPTION) {
    FileOutputStream stream = null;
    PrintStream out = null;
    try {
        File file = chooser.getSelectedFile();
        stream = new FileOutputStream(file); 
        String text = "Your String goes here";
        out = new PrintStream(stream);
        out.print(text);                  //This will overwrite existing contents

    } catch (Exception ex) {
        //do something
    } finally {
        try {
            if(stream!=null) stream.close();
            if(out!=null) out.close();
        } catch (Exception ex) {
            //do something
        }
    }
}

이 예에서는 사용자가 파일 선택기를 사용하여 파일을 선택할 수 있습니다.

private static void generateFile(String stringToWrite, String outputFile) {
    try {       
        FileWriter writer = new FileWriter(outputFile);
        writer.append(stringToWrite);
        writer.flush();
        writer.close();
        log.debug("New File is generated ==>"+outputFile);
    } catch (Exception exp) {
        log.error("Exception in generateFile ", exp);
    }
}

만약의 경우에 대비하여 라이터/출력 스트림을 최종 블록으로 닫는 것이 좋습니다.

finally{
   if(writer != null){
     try{
        writer.flush();
        writer.close();
     }
     catch(IOException ioe){
         ioe.printStackTrace();
     }
   }
}

기본적으로는 여기와 같은 대답이지만, 복사/붙여넣기가 쉽고, 동작도 간단합니다;-)

  import java.io.FileWriter;

  public void saveToFile(String data, String filename) {
    try (
      FileWriter fw = new FileWriter(filename)) {
      fw.write(data);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

제 생각에 가장 좋은 방법은,Files.write(Path path, Iterable<? extends CharSequence> lines, OpenOption... options):

String text = "content";
Path path = Paths.get("path", "to", "file");
Files.write(path, Arrays.asList(text));

javadoc 참조:

파일에 텍스트 행을 씁니다.각 행은 문자 시퀀스이며 시스템 속성 line.separator에 의해 정의된 대로 플랫폼의 행 구분자로 끝나는 각 행이 순서대로 파일에 기록됩니다.문자는 지정된 문자 집합을 사용하여 바이트로 인코딩됩니다.

options 파라미터는 파일을 작성하거나 여는 방법을 지정합니다.옵션이 없는 경우 이 방법은 CREATE, TRUNCATE_EXISTING 및 WRITE 옵션이 있는 것처럼 작동합니다.즉, 쓰기용으로 파일을 열거나 파일이 없는 경우 파일을 만들거나 기존 일반 파일을 처음에 0 크기로 잘라냅니다.이 메서드는 모든 행이 기록되었을 때(또는 I/O 오류 또는 기타 런타임 예외가 느려졌을 때) 파일이 닫히도록 합니다.I/O 오류가 발생하면 파일이 생성 또는 잘린 후 또는 파일에 일부 바이트를 쓴 후에 오류가 발생할 수 있습니다.

부디 참고하세요.이미 자바 빌트인으로 답변이 끝난 것 같습니다.Files.write하지만 아무도 언급하지 않는 듯한 제 답변에서 특별한 것은 CharSequence(문자열)의 반복(Itable of CharSequence, 즉 String)을 사용하는 메서드의 과부하 버전입니다.byte[]array,즉 「」, 「」의 순서로 설정합니다.text.getBytes()필수가 아니라 좀 더 깔끔한 것 같아요.

캐리지 리턴 문자를 문자열에서 파일로 유지하려면 다음 코드 예를 참조하십시오.

    jLabel1 = new JLabel("Enter SQL Statements or SQL Commands:");
    orderButton = new JButton("Execute");
    textArea = new JTextArea();
    ...


    // String captured from JTextArea()
    orderButton.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent ae) {
            // When Execute button is pressed
            String tempQuery = textArea.getText();
            tempQuery = tempQuery.replaceAll("\n", "\r\n");
            try (PrintStream out = new PrintStream(new FileOutputStream("C:/Temp/tempQuery.sql"))) {
                out.print(tempQuery);
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println(tempQuery);
        }

    });

모든 Android 버전에서 실행되고 URL/URI 등의 리소스가 필요하기 때문에 Stream을 기반으로 하고 있으므로 어떤 제안이라도 환영합니다.

스트림(InputStream 및 OutputStream)은 개발자가 스트림에 문자열을 쓰려고 할 때 먼저 바이트로 변환해야 하며, 다른 말로 인코딩해야 합니다.

public boolean writeStringToFile(File file, String string, Charset charset) {
    if (file == null) return false;
    if (string == null) return false;
    return writeBytesToFile(file, string.getBytes((charset == null) ? DEFAULT_CHARSET:charset));
}

public boolean writeBytesToFile(File file, byte[] data) {
    if (file == null) return false;
    if (data == null) return false;
    FileOutputStream fos;
    BufferedOutputStream bos;
    try {
        fos = new FileOutputStream(file);
        bos = new BufferedOutputStream(fos);
        bos.write(data, 0, data.length);
        bos.flush();
        bos.close();
        fos.close();
    } catch (IOException e) {
        e.printStackTrace();
        Logger.e("!!! IOException");
        return false;
    }
    return true;
}

언급URL : https://stackoverflow.com/questions/1053467/how-do-i-save-a-string-to-a-text-file-using-java

반응형