Programing

Java를 사용하여 문자열을 텍스트 파일에 어떻게 저장합니까?

lottogame 2020. 10. 2. 21:23
반응형

Java를 사용하여 문자열을 텍스트 파일에 어떻게 저장합니까?


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

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


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

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

그런 다음 출력 스트림과 마찬가지로 String을 작성하십시오.

out.println(text);

언제나처럼 예외 처리가 필요합니다. out.close()작성이 끝나면 반드시 전화하십시오 .

Java 7 이상을 사용하는 경우 " try-with-resources 문 "을 사용 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 File 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)
    {
    }
}

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

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

여기에 더 많은 정보가 있습니다 : http://www.drdobbs.com/jvm/java-se-7-new-file-io/231600403


Apache Commons IOFileUtils.writeStringToFile() 에서 사용합니다 . 이 특별한 바퀴를 재발 명 할 필요가 없습니다.


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

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();
        }
    }
}

에서 자바 (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);

Apache Commons IO api를 사용하십시오. 간단 해

API 사용

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

Maven 종속성

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

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

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.nio.file.Files;
import java.nio.file.Paths;

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

나는 이런 종류의 작업을 위해 가능할 때마다 라이브러리에 의존하는 것을 선호합니다. 이렇게하면 실수로 중요한 단계를 생략 할 가능성이 줄어 듭니다 (예 : 위에서 만든 wolfsnipes 실수). 위에 제안 된 일부 라이브러리가 있지만 이런 종류의 라이브러리를 가장 좋아하는 것은 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
}

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

이 메서드를 클래스에 삽입 할 수 있습니다. 메인 메서드가있는 클래스에서이 메서드를 사용하는 경우 정적 키워드를 추가하여이 클래스를 static으로 변경하십시오. 어느 쪽이든 작동하려면 java.io. *를 가져와야합니다. 그렇지 않으면 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 ;
    }
};

사용 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);
}

org.apache.commons.io.FileUtils 사용 :

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
        }
    }
}

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


어떤 일이 발생할 경우를 대비하여 finally 블록에서 writer / outputstream을 닫는 것이 좋습니다.

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

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);
}

}


예를 들어, ArrayList를 사용하여 TextArea의 모든 내용을 넣고 저장을 호출하여 매개 변수로 보낼 수 있습니다. 작성자가 방금 문자열 행을 작성한 다음 "for"를 한 줄씩 사용하여 마지막에 ArrayList를 작성합니다. 우리는 txt 파일의 내용 TextArea가 될 것입니다. 뭔가 말이 안된다면 구글 번역기이고 영어를 못하는 저에게 죄송합니다.

Windows 메모장을 확인하십시오. 항상 줄을 건너 뛰는 것은 아니며 모두 한 줄에 표시됩니다. 워드 패드를 사용하십시오.


private void SaveActionPerformed (java.awt.event.ActionEvent evt) {

String NameFile = Name.getText();
ArrayList< String > Text = new ArrayList< String >();

Text.add(TextArea.getText());

SaveFile(NameFile, Text);

}


public void SaveFile(String name, ArrayList< String> message) {

path = "C:\\Users\\Paulo Brito\\Desktop\\" + name + ".txt";

File file1 = new File(path);

try {

    if (!file1.exists()) {

        file1.createNewFile();
    }


    File[] files = file1.listFiles();


    FileWriter fw = new FileWriter(file1, true);

    BufferedWriter bw = new BufferedWriter(fw);

    for (int i = 0; i < message.size(); i++) {

        bw.write(message.get(i));
        bw.newLine();
    }

    bw.close();
    fw.close();

    FileReader fr = new FileReader(file1);

    BufferedReader br = new BufferedReader(fr);

    fw = new FileWriter(file1, true);

    bw = new BufferedWriter(fw);

    while (br.ready()) {

        String line = br.readLine();

        System.out.println(line);

        bw.write(line);
        bw.newLine();

    }
    br.close();
    fr.close();

} catch (IOException ex) {
    ex.printStackTrace();
    JOptionPane.showMessageDialog(null, "Error in" + ex);        

}


I think the best way is using 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));

See javadoc:

Write lines of text to a file. Each line is a char sequence and is written to the file in sequence with each line terminated by the platform's line separator, as defined by the system property line.separator. Characters are encoded into bytes using the specified charset.

The options parameter specifies how the the file is created or opened. If no options are present then this method works as if the CREATE, TRUNCATE_EXISTING, and WRITE options are present. In other words, it opens the file for writing, creating the file if it doesn't exist, or initially truncating an existing regular-file to a size of 0. The method ensures that the file is closed when all lines have been written (or an I/O error or other runtime exception is thrown). If an I/O error occurs then it may do so after the file has created or truncated, or after some bytes have been written to the file.

Please note. I see people have already answered with Java's built-in Files.write, but what's special in my answer which nobody seems to mention is the overloaded version of the method which takes an Iterable of CharSequence (i.e. String), instead of a byte[] array, thus text.getBytes() is not required, which is a bit cleaner I think.


If you wish to keep the carriage return characters from the string into a file here is an code example:

    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);
        }

    });

My way is based on stream due to running on all Android versions and needs of fecthing resources such as URL/URI, any suggestion is welcome.

As far as concerned, streams (InputStream and OutputStream) transfer binary data, when developer goes to write a string to a stream, must first convert it to bytes, or in other words encode it.

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

반응형