텍스트(.txt)파일 쓰기



java)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package com.ghj.blog_041;
 
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
 
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
 
public class MainActivity extends AppCompatActivity {
 
    final static String foldername = Environment.getExternalStorageDirectory().getAbsolutePath()+"/TestLog";
    final static String filename = "logfile.txt";
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
 
    //버튼클릭
    public void mOnFileWrite(View v){
        String now = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        String contents = "Log 생성 : "+now+"\n";
 
        WriteTextFile(foldername, filename, contents);
    }
 
    //텍스트내용을 경로의 텍스트 파일에 쓰기
    public void WriteTextFile(String foldername, String filename, String contents){
        try{
            File dir = new File (foldername);
            //디렉토리 폴더가 없으면 생성함
            if(!dir.exists()){
                dir.mkdir();
            }
            //파일 output stream 생성
            FileOutputStream fos = new FileOutputStream(foldername+"/"+filename, true);
            //파일쓰기
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(fos));
            writer.write(contents);
            writer.flush();
 
            writer.close();
            fos.close();
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}
 
cs



xml)

1
2
3
4
5
6
7
8
9
10
11
12
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
 
    <Button
        android:text="파일쓰기"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="mOnFileWrite"/>
</LinearLayout>
 
cs



AndroidManifest.xml)

1
2
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
 
cs



결과


+ Recent posts