마스터Q&A 안드로이드는 안드로이드 개발자들의 질문과 답변을 위한 지식 커뮤니티 사이트입니다. 안드로이드펍에서 운영하고 있습니다. [사용법, 운영진]

txt 저장된것 불러올 때 개행형식으로 불러오기

0 추천

txt 파일을 저장하고, 읽어들이고 삭제하는 앱입니다

아래 소스는 통째로 그대로 올렸구요

몇가지 문제가 있더라구요

 

1) txt 파일을 저장하고 컴퓨터와 안드로이드 장치를 연결해서 탐색기로 해당 저장된 폴더

TEST_TEXT_WRITE에 가면 제가 저장한 txt파일들이 안보이더라구요.

그런데 몇일뒤? 다시연결해보면 제가 저장했던 txt파일들이 있더라구요.

실시간으로 저장한게 보이지가 않고 나중에 보이던데.. 소스상에 뭐가 문제일까요?...

 

2) edittext 에 글자를 

학교에

갑니다

식으로 엔터를 여러번 쳐서 저장을 한뒤, 열기를 눌러 해당 파일을 열면

학교에갑니다식으로 나오네요..

저장한 파일에 탐색기로 보면 엔터영역으로 지정이 되어 있는것 같은데,

앱상에서 열기상에서도 엔터 개행이 정확히 잘되어서 나오게 하려면 어떻게 해야할까요?

 

 

 

* MainActivity.java ( 안드로이드 매니페스트에 write_external_storage 쓰기권한 읽기권한 두개 줬습니다 )  

public class MainActivity extends Activity {
    /** Called when the activity is first created. */

    private String path;//저장하는 곳의 경로
    private EditText ed1;//제목 적는 EditText
    private EditText ed2;//내용 적는 EditText
    private Button bt1;//저장하기 버튼
    private Button bt2;//불러오기 버튼
    private Button bt3;//삭제하기 버튼

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        path = Environment.getExternalStorageDirectory().getAbsolutePath()+File.separator+"/TEST_TEXT_WRITE";

        ed1 = (EditText)findViewById(R.id.ed1);
        ed2 = (EditText)findViewById(R.id.ed2);
        bt1 = (Button)findViewById(R.id.bt1);
        bt2 = (Button)findViewById(R.id.bt2);
        bt3 = (Button)findViewById(R.id.bt3);

        bt1.setOnClickListener(btListener);
        bt2.setOnClickListener(btListener);
        bt3.setOnClickListener(btListener);
    }
    Button.OnClickListener btListener = new Button.OnClickListener(){
        public void onClick(View v) {
            // TODO Auto-generated method stub
            switch(v.getId()){
                case R.id.bt1:
                    String ed1text = ed1.getText().toString().trim();
                    if(ed1text.length()>0){
                        onTextWriting(ed1text,ed2.getText().toString());
                    }
                    break;
                case R.id.bt2:
                    onTextRead();
                    break;
                case R.id.bt3:
                    deltext();
                    break;
            }
        }

    };
    private void onTextWriting(String title,String body){
        File file;
        file = new File(path);
        if(!file.exists()){
            file.mkdirs();
        }
        file = new File(path+File.separator+title+".txt");
        try{
            FileOutputStream fos = new FileOutputStream(file);
            BufferedWriter buw = new BufferedWriter(new OutputStreamWriter(fos, "UTF8"));
            buw.write(body);
            buw.close();
            fos.close();
            Toast.makeText(this, "저장되었습니다.", Toast.LENGTH_SHORT).show();
        }catch(IOException e){

        }
    }
    private void onTextRead(){
        final ArrayList<File> filelist = new ArrayList<File>();
        File files = new File(path);
        if(!files.exists()){
            files.mkdirs();
        }
        if(files.listFiles().length>0){
            for(File file : files.listFiles(new TextFileFilter())){
                filelist.add(file);
            }
        }
        CharSequence[] filename = new CharSequence[filelist.size()];
        for(int i = 0 ; i < filelist.size() ; i++){
            filename[i] = filelist.get(i).getName();
        }
        new AlertDialog.Builder(this)
                .setTitle("TEXT FILE LIST")
                .setItems(filename, new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface arg0, int arg1) {
                        // TODO Auto-generated method stub
                        try{
                            String body = "";
                            StringBuffer bodytext = new StringBuffer();
                            File selecttext = filelist.get(arg1);
                            FileInputStream fis = new FileInputStream(selecttext);
                            BufferedReader bufferReader = new BufferedReader(new InputStreamReader(fis,"UTF-8"));
                            while((body = bufferReader.readLine())!=null){
                                bodytext.append(body);
                            }
                            ed1.setText(selecttext.getName());
                            ed2.setText(bodytext.toString());
                        }catch(IOException e){

                        }
                    }
                }).setNegativeButton("취소", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub

            }
        }).show();
    }
    private void deltext(){
        final ArrayList<File> filelist = new ArrayList<File>();
        File files = new File(path);
        if(!files.exists()){
            files.mkdirs();
        }
        if(files.listFiles().length>0){
            for(File file : files.listFiles(new TextFileFilter())){
                filelist.add(file);
            }
        }
        CharSequence[] filename = new CharSequence[filelist.size()];
        for(int i = 0 ; i < filelist.size() ; i++){
            filename[i] = filelist.get(i).getName();
        }
        new AlertDialog.Builder(this)
                .setTitle("TEXT FILE LIST")
                .setItems(filename, new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface arg0, int arg1) {
                        // TODO Auto-generated method stub
                        filelist.get(arg1).delete();
                        deltext();
                    }
                }).setNegativeButton("취소", new DialogInterface.OnClickListener() {

            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub

            }
        }).show();
    }
    class TextFileFilter implements FileFilter{
        public boolean accept(File file) {
            // TODO Auto-generated method stub
            if(file.getName().endsWith(".txt"))return true;
            return false;
        }
    }
}

 

* activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <EditText
        android:id="@+id/ed1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="제목을 적으세요!"
        />
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        >
        <Button
            android:id="@+id/bt1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="저장"/>
        <Button
            android:id="@+id/bt2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="열기"/>
        <Button
            android:id="@+id/bt3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="삭제"/>
    </LinearLayout>
    <EditText
        android:id="@+id/ed2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="내용을 적으세요!"/>
</LinearLayout>

 

shaoming (160 포인트) 님이 2016년 2월 19일 질문

답변 달기

· 글에 소스 코드 보기 좋게 넣는 법
· 질문에 대해 추가적인 질문이나 의견이 있으면 답변이 아니라 댓글로 달아주시기 바랍니다.
표시할 이름 (옵션):
개인정보: 당신의 이메일은 이 알림을 보내는데만 사용됩니다.
스팸 차단 검사:
스팸 검사를 다시 받지 않으려면 로그인하거나 혹은 가입 하세요.
...