将扫描的条形码数据保存到txt文件

时间:2017-08-06 19:10:41

标签: android string textview

我需要帮助将扫描的条形码数据保存到一个txt文件(我知道你会建议我通过SharedPreferences保存它,但我需要它很简单) 所以基本上当我扫描代码时,它的数据应保存在手机上的txt文件中。这是代码:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private Button scanBtn;
    private TextView formatTxt, contentTxt;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        scanBtn = (Button)findViewById(R.id.scan_button);
        formatTxt = (TextView)findViewById(R.id.scan_format);
        contentTxt = (TextView)findViewById(R.id.scan_content);
        scanBtn.setOnClickListener(this);
    }
    public void onClick(View v){
        if(v.getId()==R.id.scan_button){
            IntentIntegrator scanIntegrator = new IntentIntegrator(this);
            scanIntegrator.initiateScan();
        }
    }
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
        if (scanningResult != null) {
            String scanContent = scanningResult.getContents();
            String scanFormat = scanningResult.getFormatName();
            formatTxt.setText("FORMAT: "+scanFormat);
            contentTxt.setText("CONTENT: "+scanContent);
        }
        else{
            Toast toast = Toast.makeText(getApplicationContext(),
                    "No scan data received!", Toast.LENGTH_SHORT);
            toast.show();

        }
    }



}

1 个答案:

答案 0 :(得分:0)

试试这个:

try {
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput("data.txt", Context.MODE_PRIVATE));
        outputStreamWriter.write(scanContent);
        outputStreamWriter.close();
    }
    catch (IOException e) {
        Log.e("Exception", "File write failed: " + e.toString());
    }

<强>更新

其他方式,可以写入sdcard

try {
            File myFile = new File("/sdcard/data.txt");
            myFile.createNewFile();
            FileOutputStream fOut = new FileOutputStream(myFile);
            OutputStreamWriter myOutWriter = 
                                    new OutputStreamWriter(fOut);
            myOutWriter.append(scanContent);
            myOutWriter.close();
            fOut.close();
            Toast.makeText(yourActivity.this,
                    "File created'mysdfile.txt'",
                    Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            Toast.makeText(yourActivity.this, e.getMessage(),
                    Toast.LENGTH_SHORT).show();
        }

不要忘记添加permision:

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