IT TIP

텍스트 파일 작성 방법 Java

itqueen 2020. 11. 29. 12:49
반응형

텍스트 파일 작성 방법 Java


다음 코드는 파일을 생성하지 않습니다 (파일을 어디에서도 볼 수 없습니다). 없어진 물건 있어요?

try {
    //create a temporary file
    String timeLog = new SimpleDateFormat("yyyyMMdd_HHmmss").format(
        Calendar.getInstance().getTime());
    File logFile=new File(timeLog);

    BufferedWriter writer = new BufferedWriter(new FileWriter(logFile));
    writer.write (string);

    //Close writer
    writer.close();
} catch(Exception e) {
    e.printStackTrace();
}

나는 당신의 기대와 현실이 일치하지 않는다고 생각합니다.

기본적으로 파일이 작성되었다고 생각하는 위치와 파일이 실제로 작성되는 위치는 동일하지 않습니다 (음, 아마도 if문장을 작성해야 합니다;))

public class TestWriteFile {

    public static void main(String[] args) {
        BufferedWriter writer = null;
        try {
            //create a temporary file
            String timeLog = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
            File logFile = new File(timeLog);

            // This will output the full path where the file will be written to...
            System.out.println(logFile.getCanonicalPath());

            writer = new BufferedWriter(new FileWriter(logFile));
            writer.write("Hello world!");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // Close the writer regardless of what happens...
                writer.close();
            } catch (Exception e) {
            }
        }
    }
}

또한 예제는 기존 파일을 덮어 씁니다. 파일에 텍스트를 추가하려면 대신 다음을 수행해야합니다.

writer = new BufferedWriter(new FileWriter(logFile, true));

MadProgrammer의 답변에 조금 더 추가하고 싶습니다.

여러 줄 쓰기의 경우 명령 실행시

writer.write(string);

개행 문자가 디버깅 중에 나타나거나 동일한 텍스트가 터미널에 인쇄되는 경우에도 작성된 파일에서 생략되거나 건너 뛴다는 것을 알 수 있습니다.

System.out.println("\n");

따라서 전체 텍스트는 대부분의 경우 바람직하지 않은 하나의 큰 텍스트 덩어리로 제공됩니다. 개행 문자는 플랫폼에 따라 달라질 수 있으므로 다음을 사용하여 Java 시스템 속성에서이 문자를 가져 오는 것이 좋습니다.

String newline = System.getProperty("line.separator");

그런 다음 "\ n"대신 개행 변수를 사용합니다. 원하는 방식으로 출력을 얻을 수 있습니다.


Java 7에서 이제 할 수 있습니다.

try(BufferedWriter w = ....)
{
  w.write(...);
}
catch(IOException)
{
}

w.close가 자동으로 수행됩니다.


실제로 파일을 만든 적이 없기 때문에 파일을 만드는 것이 아닙니다. 당신은 그것을 위해 물건을 만들었습니다. 인스턴스를 만들어도 파일이 만들어지지는 않습니다.

File newFile = new File("directory", "fileName.txt");

이렇게하면 파일을 만들 수 있습니다.

newFile.createNewFile();

이렇게하면 폴더를 만들 수 있습니다.

newFile.mkdir();

Java 라이브러리를 사용해 볼 수 있습니다. FileUtils , 파일에 쓰는 많은 기능이 있습니다.


It does work with me. Make sure that you append ".txt" next to timeLog. I used it in a simple program opened with Netbeans and it writes the program in the main folder (where builder and src folders are).


Using java 8 LocalDateTime and java 7 try-with statement:

public class WriteFile {

    public static void main(String[] args) {

        String timeLog = DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss").format(LocalDateTime.now());
        File logFile = new File(timeLog);

        try (BufferedWriter bw = new BufferedWriter(new FileWriter(logFile))) 
        {
            System.out.println("File was written to: "  + logFile.getCanonicalPath());
            bw.write("Hello world!");
        } 
        catch (IOException e) 
        {
            e.printStackTrace();
        }
    }
}

The easiest way for me is just like:

            try {
                FileWriter writer = new FileWriter("C:/Your/Absolute/Path/YourFile.txt");
                writer.write("Wow, this is so easy!");
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

Useful tips & tricks:

  • Give it a certain path:

    new FileWriter("C:/Your/Absolute/Path/YourFile.txt");

  • New line

    writer.write("\r\n");

  • Append lines into existing txt

    new FileWriter("log.txt");

Hope it works!

참고URL : https://stackoverflow.com/questions/15754523/how-to-write-text-file-java

반응형