簡體   English   中英

嘗試在Eclipse中寫入讀寫文本文件

[英]trying to write to read and write to a text file in 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();
        }
    }               
}

}); //結束后退按鈕

}

}

公共類MainActivity擴展了Activity {TextView fDisplay; TextView fTest; int numItems = 0; //稍后使用它來跟蹤項目數。 字符串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
            }
        }
    }



    }

}`

為了在文件上寫,我使用了這個

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";
    }
}

在Android中,文件的目錄不同於PC上的目錄,例如:文件存儲在與您的App相關的目錄中,訪問權限也不同。 該鏈接可能會有所幫助:

如何在Android中從文件讀取/寫入字符串

可以讀取和編寫兩個簡單的函數(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;
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM