试图在eclipse中写入读写文本文件

时间:2015-10-10 09:31:55

标签: java android eclipse

我正在尝试编写和阅读文本文件名学生,但我有各种麻烦我是Android编程的新手,所以我第一次尝试这个。我已经看过这里和那里的代码,试图弄清楚我做错了什么,但是我找不到一个具体的东西可以提供帮助,这个问题可能已被问过几次,所以我很抱歉再次询问。请参阅下面我的不同.xml和.java文件。实际的问题是能够将数据写入文本文件,并从主屏幕单击文本字段,该文本字段将带您进入编辑屏幕,您可以在其中编辑该特定字段并将其保存到文本文件(但是还没有完成,因为我仍在努力弄清楚为什么我的文字文件的写作和阅读不起作用,我希望我对编码的不良尝试能够解释这个问题。 请不要因为我的错误编码而把我钉在十字架上我是android的新手

/////////////////////////////add screen.java///////////////////////////////

public class AddNew extends Activity {
private static final String newLine = System.getProperty("line.separator");
TextView txtText; 
EditText Modules;
EditText Types;

@Override
protected void onCreate(Bundle SavedInstanceState){
    super.onCreate(SavedInstanceState);
    setContentView(R.layout.add);

    txtText = (TextView)findViewById(R.id.textView1);
    Modules = (EditText)findViewById(R.id.etMod);
    Types = (EditText)findViewById(R.id.etType);

Button backMan = (Button)findViewById(R.id.btnBackMain);
backMan.setOnClickListener(new OnClickListener(){
  public void onClick(View v){
  //This is where your code will go
      startActivity(new Intent(AddNew.this, MainActivity.class));
  }
});  //end back Button

//get the day, month & year from the Date picker
DatePicker myDPicker = (DatePicker)findViewById(R.id.dpDate);
Integer Year = myDPicker.getYear();
Integer Month = myDPicker.getMonth();
Integer Day = myDPicker.getDayOfMonth();
StringBuilder sb = new StringBuilder();
sb.append(Year.toString()).append("-").append(Month.toString()).append
("-").append(Day.toString());
final String dobStr=sb.toString();

txtText.setText("TEST");

Button Save = (Button)findViewById(R.id.btnSaveAdded);
Save.setOnClickListener(new OnClickListener(){
public void onClick(View v){
 //This is where your code will go       
try {
    writeToFile(Modules.getText().toString(),    
Types.getText().toString(),dobStr);

} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}    
 }

private void writeToFile(String Mod, String AsType, String dobDate) throws
 IOException {
    // TODO Auto-generated method stub
    //String textTofile;
    StringBuilder sbText = new StringBuilder();
    sbText.append(Mod + "," + dobStr + "," + AsType);
    //textTofile=sbText.toString();


        String fileName = "student";
        PrintWriter printWriter = null;
        File file = new File(fileName);
        try {
            if (!file.exists()) file.createNewFile();
            printWriter = new PrintWriter(new FileOutputStream(fileName, 
        true));
            printWriter.write(newLine ); //+textTofile);
        } catch (IOException ioex) {
            ioex.printStackTrace();
        } finally {
            if (printWriter != null) {
                printWriter.flush();
                printWriter.close();
        }
    }               
}

}); //结束按钮

}

}

`public class MainActivity extends Activity {      TextView fDisplay;      TextView fTest;      int numItems = 0; //稍后使用它来跟踪项目数量。      String inText; //将此变量用于从文本文件中读取的信息。

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

    Button but1=(Button)findViewById(R.id.btnAdd);
    but1.setOnClickListener(new OnClickListener(){

      public void onClick(View v){
      //This is where your code will go
          startActivity(new Intent(MainActivity.this, AddNew.class));
      }
    });  //end but1

    Button but2 = (Button)findViewById(R.id.btnEditCur);
    but2.setOnClickListener(new OnClickListener(){

      public void onClick(View v){
      //This is where your code will go
          startActivity(new Intent(MainActivity.this, EditCur.class));
      }
    });  //end of button 2

    fDisplay = (TextView)findViewById(R.id.tvAssign1); 


    try {
    readFromFile();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } 

}

private void readFromFile() throws IOException {
     // TODO Auto-generated method stub
    // String ret="";
    BufferedReader br;
    FileReader fr = null;
    try {
        fr = new FileReader("student");
        br = new BufferedReader(fr);
        String line = br.readLine();
        while (null != line) {
            fDisplay.append(line);
            fDisplay.append("\n");
            line = br.readLine();
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        if (null != fr) {
            try {
                fr.close();
            } catch (IOException e) {
                // ignore
            }
        }
    }



    }

} `

3 个答案:

答案 0 :(得分:0)

对于文件的写入,我使用了这个

String filename;
String content;

filename = "PATH_AND_FILE";
content = "CONTENT ON THE FILE"

BufferedWriter out = new BufferedWriter(new FileWriter(filename));
                            out.write(myString.toString());  
                            out.flush();  
                            out.close(); 

为了阅读我有这个功能:

public static String readFileAsString() {
    String result = "";
String filename;

filename = "PATH_AND_FILE";
    File file = new File(filename);
    if ( file.exists() ) {
        FileInputStream fis = null;
        try {                   fis = new FileInputStream(file);
            char current;
            while (fis.available() > 0) {
                current = (char) fis.read();
                result = result + String.valueOf(current);
            }
        } catch (Exception e) {
            // System.out.println("DEBUG Exception String :"+ e.toString());
        } finally {
            if (fis != null)
            { try {
                fis.close();
            } catch (IOException ignored) {
            }}
            else {// System.out.println("DEBUG Exception String NULL");
            }
        }
        return result;
    }
    else
    {
        return "DEFAULT CONTENT";
    }
}

答案 1 :(得分:0)

在Android中,文件'目录与PC上的目录不同,例如:文件存储在与您的App相关的目录中,访问权限不同。 此链接可能会有所帮助:

How To Read/Write String From A File In Android

答案 2 :(得分:0)

两个简单的函数(Java)来读写:

private static void writeToFile(String path, String text) {
        PrintWriter writer;
        try {
            writer = new PrintWriter(path, "UTF-8");
            writer.print(text);
            writer.close();
        } catch (FileNotFoundException | UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }


public static String getFileContent(String filename){
        String everything = "";
        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader(filename));
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            StringBuilder sb = new StringBuilder();
            String line = null;
            try {
                line = br.readLine();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            while (line != null) {
                sb.append(line);
                sb.append(System.lineSeparator());
                try {
                    line = br.readLine();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            everything = sb.toString();
        } finally {
            try {
                br.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return everything;
    }