자바 파일 입출력 질문드려요

revol2236의 이미지

제가 만들고 싶은 부분은 기존 파일에 있는 부분에 덧붙여서 다른 내용을 저장하는 것인데요

예를들어 data.txt 라는 텍스트 파일에
kldp.org 라는 내용이 써져있다면 다시한번 프로그램을 실행시킬때는

kldp.org 라는 내용아래에
linux 라는 문자가 추가 되는 형식 입니다,, 그런데 어쩐지 컴파일은 되는데 실행할때

오류가 뜨네요,,

문제가 뭔지 알려주시면 감사하겠습니다,,,

import java.util.StringTokenizer;
import java.io.*;
 
class JAVA_File {
 
public static void main(String[] args){
	try{
			File imsifile = new File("./file_pra/data2.txt");
		String s = "캐릭터 정보";
		String k;
 
			BufferedReader an = new BufferedReader(new FileReader(imsifile));
 
		File filename = new File("./file_pra/data.txt");
		BufferedReader ow = new BufferedReader(new FileReader(filename));
 
		System.out.println(ow.readLine());
		k=ow.readLine();	
		if(k==""){
			BufferedWriter wr = new BufferedWriter(new FileWriter("./file_pra/data.txt"));
			System.out.println(ow.readLine());
			wr.write(s);
			wr.newLine();
			wr.close();
		}
		else{
			BufferedWriter ir = new BufferedWriter(new FileWriter(imsifile));
			do{
				ir.write(ow.readLine());
				ir.newLine();
			}while(ow.readLine()!=null);
			ir.write(s);
			ir.close();
			BufferedWriter wr = new BufferedWriter(new FileWriter("./file_pra/data.txt"));
			do{
				wr.write(an.readLine());
				wr.newLine();
			}while(an.readLine()!=null);
				wr.close();
		}
 
	}catch(Exception ex){
		ex.printStackTrace();
	}
	}
}
 
leafriend의 이미지

FileReader 인스턴스를 두 번 만들고 있네요. (new FileReader(imsifile) & new FileWriter("./file_pra/data.txt")) 기존 소스를 수정하는 것보다 새로 짜는 게 낫겠다 싶어서 작성해 봤습니다.

package tmp;

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

public class KldpQuestion128407 {

    public static void main(String[] args) {

        String filename = "data.txt";
        String charset = "UTF-8";
        String text = "linux";

        Writer writer = null;

        try {

            writer = new OutputStreamWriter(
                    new FileOutputStream(filename, true), charset);
            writer.append(text + "\n");

        } catch (IOException e) {
            e.printStackTrace();

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

    }

}
leafriend의 이미지

한 가지 첨언하자면, 파일을 다루 실 때는 항상 캐릭터셋을 명시해주시는 게 나중에 받을 스트레스를 줄일 수 있습니다. :)

revol2236의 이미지

원래 하려던게

기존 파일에서 임시파일로 내용을 복사하고

제가 같이 입력하고 싶던 부분을 추가 하느것,, 그리고 다시 임시파일 내용을 기존 파일에 복사하는 것이였는 데요,,

이런 멋들어지고 간단한 방법이 있었군요 감사합니다

============================================

비가오면 사람들은 눈물흘리고

그빗물에 흘러내린 눈물감추고

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.