【问题标题】:Android OutputStreamWriter not creating fileAndroid OutputStreamWriter 不创建文件
【发布时间】:2012-07-11 17:30:07
【问题描述】:

我正在尝试将数据从 EditText 字段写入文本文件。我已验证数据正在被捕获以在单击“添加”按钮后填充的 EditText 字段中输出。程序在模拟器中成功运行,但没有创建输出文件。我已将 uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" 添加到 Android Manifest xml 文件中。 LogCat 和控制台不显示任何错误。在这里研究示例后,我尝试了几种不同的方法,但没有运气。谁能指出我的问题?提前感谢您的帮助。

package john.BRprogram;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.EditText;
//import android.graphics.Color;
import java.io.OutputStreamWriter;
import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;

public class BRprogramActivity extends Activity implements OnItemSelectedListener {
  private static final String TAG = null;
//
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
 //
    Button addButton;
    Button editButton;
    Button sendButton;
//  
    Spinner array_spinner;
//      
//      activate soft Keyboard
    this.getWindow().setSoftInputMode
      (WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); 
//
    EditText myCustomer = (EditText)findViewById(R.id.editText1);
    myCustomer.setText("");   
//
    EditText myQuantity = (EditText)findViewById(R.id.editText2);
    myQuantity.setText("");
//      
    EditText myPrice = (EditText)findViewById(R.id.editText3);
    myPrice.setText("");
//    
//      .csv comma separated values file
//        
    try {
        Scanner scanner = new Scanner(getResources().openRawResource(R.raw.brdata));  
//         
        List<String> list = new ArrayList<String>(); 
        while (scanner.hasNext()) {
        String data = (scanner.next());                  //read data record
        String [] values = data.split(",");           //parse data to fields
//      String [] values = data.split(",(?=([^\"]\"[^\"]\")[^\"]$)");
        if(values.length != 3)     
            Log.v("Example", "Malformed row: " + data); 
            else  
            list.add(values[0] + " " + values[1] + " $" + values[2]);
}
//          
        array_spinner = (Spinner)findViewById(R.id.spinner1);         
        ArrayAdapter<String> adapter = new ArrayAdapter<String>
        (this,android.R.layout.simple_spinner_item, list);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 
        array_spinner.setAdapter(adapter); 
        array_spinner.setOnItemSelectedListener((OnItemSelectedListener) this);
//           
        scanner.close();
//    
}   catch (Exception e) {
        Log.e(TAG, "Exception: "+Log.getStackTraceString(e));
}
//
    addButton = (Button) findViewById(R.id.addbutton);
    addButton.setOnClickListener(new OnClickListener(){
        public void onClick(View v){
//    
// get customer number,itemnumber,quantity,price
//
    String writeCustomer = ((EditText) findViewById(R.id.editText1)).getText().toString().trim();
//  itemNumber from list selection
    String writeQuantity = ((EditText) findViewById(R.id.editText2)).getText().toString().trim();
    String writePrice = ((EditText) findViewById(R.id.editText3)).getText().toString().trim();
//
    String newRecord = writeCustomer + "," + writeQuantity + "," + writePrice; 

    EditText myString = (EditText)findViewById(R.id.editText4);
    myString.setText(newRecord);        
//          
// write seq to output file             
//              
    try {
        OutputStreamWriter out = new OutputStreamWriter(openFileOutput("broutput.txt",0));
        out.write(newRecord);   
        out.close(); 
    }catch (Exception e){
      Log.v("test", "record written");
}                       

//
            EditText myQuantity = (EditText)findViewById(R.id.editText2);
            myQuantity.setText("");
//      
            EditText myPrice = (EditText)findViewById(R.id.editText3);
            myPrice.setText("");
            Log.v("test", "ADD button clicked");
}
});
//
    editButton = (Button) findViewById(R.id.editbutton);
    editButton.setOnClickListener(new OnClickListener(){
        public void onClick(View v){
            Log.v("test", "EDIT button clicked");
}
});    
//
    sendButton = (Button) findViewById(R.id.sendbutton);
    sendButton.setOnClickListener(new OnClickListener(){
        public void onClick(View v){
//
            EditText myCustomer = (EditText)findViewById(R.id.editText1);
            myCustomer.setText("");
//
            EditText myQuantity = (EditText)findViewById(R.id.editText2);
            myQuantity.setText("");
//      
            EditText myPrice = (EditText)findViewById(R.id.editText3);
            myPrice.setText("");
            Log.v("test", "SEND button clicked");
}
});

}
//  ***  http://www.youtube.com/watch?v=Pfasw0bbe_4  ***
//
    public void onItemSelected(AdapterView<?> parent, View view, int position,
            long id) {
//  
    String selection = parent.getItemAtPosition(position).toString();
    String [] priceField = selection.split("\\$");       //parse price field
    String [] item = selection.split("_");         //parse item number 
    String itemNumber = item[0];   
//
    EditText myQuantity = (EditText)findViewById(R.id.editText2);
    myQuantity.setText("");
//      
    EditText myPrice = (EditText)findViewById(R.id.editText3);
    myPrice.setText(priceField[1]);
}
//
   public void onNothingSelected(AdapterView<?> arg0) {
//nothing here      
}
}

【问题讨论】:

  • 我认为您不需要 WRITE_EXTERNAL_STORAGE 权限,因为您只是在写入应用程序私有的文件。如果是这种情况,您通常无法在文件管理器中导航到该文件,因为它是您的应用程序私有的。你100%确定它不是被创造出来的吗?抛出了什么Exception,如果有的话?顺便说一句,最好使用常量名,而不是它们的整数值,所以当你打开文件时,使用openFileOutput("broutput.txt", Context.MODE_PRIVATE);

标签: android file


【解决方案1】:

看起来您需要创建和/或指定要保存文件的目录。我在您的代码中的任何地方都没有看到。它可能看起来像这样:

if (Environment.getExternalStorageState() == null) {
            directory = new File(Environment.getDataDirectory()
                    + "/RobotiumTestLog/");
            photoDirectory = new File(Environment.getDataDirectory()
                    + "/Robotium-Screenshots/");
            /*
             * this checks to see if there are any previous test photo files
             * if there are any photos, they are deleted for the sake of
             * memory
             */
            if (photoDirectory.exists()) {
                File[] dirFiles = photoDirectory.listFiles();
                if (dirFiles.length != 0) {
                    for (int ii = 0; ii <= dirFiles.length; ii++) {
                        dirFiles[ii].delete();
                    }
                }
            }
            // if no directory exists, create new directory
            if (!directory.exists()) {
                directory.mkdir();
            }

            // if phone DOES have sd card
        } else if (Environment.getExternalStorageState() != null) {
            // search for directory on SD card
            directory = new File(Environment.getExternalStorageDirectory()
                    + "/RobotiumTestLog/");
            photoDirectory = new File(
                    Environment.getExternalStorageDirectory()
                            + "/Robotium-Screenshots/");
            if (photoDirectory.exists()) {
                File[] dirFiles = photoDirectory.listFiles();
                if (dirFiles.length > 0) {
                    for (int ii = 0; ii < dirFiles.length; ii++) {
                        dirFiles[ii].delete();
                    }
                    dirFiles = null;
                }
            }
            // if no directory exists, create new directory to store test
            // results
            if (!directory.exists()) {
                directory.mkdir();
            }
        }

当您从应用保存数据时,您必须记住它是在 Android 上运行,而不是在您的计算机上,因此所有数据都将写入您的 Android,而不是您的计算机。您必须在写入数据后拉取数据才能查看它。确保您在设备上创建了一个本地目录,并确保您检查了 SD 卡。我列出的代码将向您展示如何做您需要的一切。

希望这会有所帮助!

【讨论】:

  • 我指定了完整的目录路径:OutputStreamWriter out = new OutputStreamWriter(openFileOutput("/Documents and Settings/Owner/workspace/BRprogram/res/raw/broutput.txt", Context.MODE_PRIVATE)) ;文件没有输出,但我确实在 Logcat 中得到了一个新的“捕获异常 - 记录未写入”。有没有更好的方法来准确查看异常是什么?
  • 您无法写入原始文件。这就是为什么你有你的问题。您需要将其保存到本地设备,而不是开发文件。您不是保存到计算机,而是保存到设备。使用我上面列出的一些代码,你应该没问题。试一试,看看会发生什么。
  • 我只在模拟器上运行它,还没有达到将它放在安卓手机上的地步。 “本地设备”是指模拟器吗?我开始怀疑这一点,并发现了一些从 AVD 设备“推/拉”的 adb 命令。非常感谢您的建议。我会试试你的代码。
  • 是的,或者您正在运行它的任何设备。我不知道你是否可以将数据写入模拟器,你可能可以,但我没有尝试过。这就是为什么我总是使用真实设备进行开发。上面的代码将起作用,如果您有任何其他问题,请告诉我。我很乐意提供帮助。如果可行,请随意投票和/或接受答案:)
  • Blaine,我导入了 android.os.Environment 和 java.io.file。编译器一直对我咆哮“目录”和“照片目录”。请问你是如何在你的程序中定义它们的?
【解决方案2】:

我实际上遇到过这样的问题;一切似乎都很好,但我的代码不起作用。我的问题是我正在编写的文件名中的字符。例如,我尝试编写文件名my_file - date 07/11/2012。这会导致问题,因为它将每个/ 视为开始新目录的提示!出于这个原因,我发现我的文件名中没有任何/(或:,出于某种原因)。这会是你的问题吗?

如果这是您的问题,那么您可以按照我的做法:执行 newRecord.replace('/', '-'); 以将文件名中的所有 / 替换为 -(如果您可以使用 - 代替)。

在旁注中,您为什么要在 try/catch 语句的 catch 中记录“记录写入”?如果它发现了问题,那不就意味着它没有被写出来吗?

【讨论】:

  • 按照建议更改了 openFileOutput 并删除了 Manifest xml 条目。没有记录异常并且没有创建文件。还按照建议修改了输出数据字符串。原始输出为 12345,999,.55 新数据为 12345999.55 认为逗号可能是特殊字符。结果相同,没有创建文件。运行 dos 提示命令 DIR/s broutput.txt 以验证该文件不在系统上。 LogCat 或控制台中没有错误条目。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多