2017-08-06 79 views
-1

我需要幫助將掃描的條碼數據保存到一個txt文件(我知道你會推薦我通過SharedPreferences保存它,但我需要它很簡單) 因此,基本上當我掃描代碼其數據應該保存在手機上的txt文件中。這裏是代碼:將掃描的條碼數據保存到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(); 

     } 
    } 



} 

回答

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()); 
    } 

UPDATE

其他方式,可能寫SD卡

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" /> 
+0

評論是不適用於擴展討論;這個對話已經[轉移到聊天](http://chat.stackoverflow.com/rooms/151304/discussion-on-answer-by-bruno-ferreira-saving-scanned-barcode-data-to-txt-file) 。 –