Android:将文本文件写入存储多长时间?

时间:2014-08-24 20:18:39

标签: php android file upload

在我Activity的{​​{1}}内我尝试使用Android Applicationtext filesstorage on device上传到服务器。

这些文件是在玩游戏时在之前的活动中生成的。

然而,当我尝试上传它们时,我从我的代码中收到以下异常消息:

PHP script然后显示应该上传的文件名的路径

我知道文件正在生成,因为我可以在设备存储上看到它们。我也知道上传到服务器的功能正常,因为我已经使用几天前创建的文件对其进行了测试。

基本上我想知道:

在下一个活动尝试上传之前,上一个活动中的文件"Source file not exist"是否已上传?即写入存储需要fully created吗?

延迟执行上传功能的线程会解决问题吗?

上传文件的活动:(注意:文件名作为附加活动传递给下一个活动)

how long

修改

创建文件的上一个活动:

创建文件的方法(全部4个相同):

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mathsgameresults);

        initialiseVars();
        setAllTextViews();

         messageText  = (TextView)findViewById(R.id.mathsresultsservertext);

            messageText.setText("Uploading file path :- '/storage/sdcard0/files/"+fileNameRaw
                    +"','/storage/sdcard0/ files/"+fileNameEEGPower+"','/storage/sdcard0/files/"+fileNameMeditation+"','/storage/sdcard0/files/"+fileNameAttention+"' ");

            //url to php script on server
            upLoadServerUri = " my url in here (not shown)";

            //remove this if not wanted to show.
            dialog = ProgressDialog.show(MathsGameResults.this, "", "Uploading files...", true);

            //logic to upload files in new thread
            new Thread(new Runnable() {
                public void run() {
                     runOnUiThread(new Runnable() {
                            public void run() {
                                messageText.setText("uploading started.....");
                            }
                        });                      

                     uploadFile(uploadFilePath + "" + fileNameRaw);                       
                     uploadFile(uploadFilePath + "" + fileNameEEGPower);                       
                     uploadFile(uploadFilePath + "" + fileNameMeditation);                       
                     uploadFile(uploadFilePath + "" + fileNameAttention);                       

                }
              }).start();     




    }

 public int uploadFile(String sourceFileUri) {


              final String fileName = sourceFileUri;

              HttpURLConnection conn = null;
              DataOutputStream dos = null;  
              String lineEnd = "\r\n";
              String twoHyphens = "--";
              String boundary = "*****";
              int bytesRead, bytesAvailable, bufferSize;
              byte[] buffer;
              int maxBufferSize = 1 * 1024 * 1024; 
              final File sourceFile = new File(sourceFileUri); 



              if (!sourceFile.isFile()) {

                   dialog.dismiss(); 

                   Log.e("uploadFile", "Source File not exist :"
                                        + sourceFileUri);

                   runOnUiThread(new Runnable() {
                       public void run() {
                           messageText.setText("Source File not exist :"
                                    + fileName);
                       }
                   }); 

                   return 0;

              }
              else
              {
                   try { 

                         // open a URL connection to the Servlet
                       FileInputStream fileInputStream = new FileInputStream(sourceFile);
                       URL url = new URL(upLoadServerUri);

                       // Open a HTTP  connection to  the URL
                       conn = (HttpURLConnection) url.openConnection(); 
                       conn.setDoInput(true); // Allow Inputs
                       conn.setDoOutput(true); // Allow Outputs
                       conn.setUseCaches(false); // Don't use a Cached Copy
                       conn.setRequestMethod("POST");
                       conn.setRequestProperty("Connection", "Keep-Alive");
                       conn.setRequestProperty("ENCTYPE", "multipart/form-data");
                       conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
                       conn.setRequestProperty("uploaded_file", fileName); 

                       dos = new DataOutputStream(conn.getOutputStream());

                       dos.writeBytes(twoHyphens + boundary + lineEnd); 
                       dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
                                                 + fileName + "\"" + lineEnd);

                       dos.writeBytes(lineEnd);

                       // create a buffer of  maximum size
                       bytesAvailable = fileInputStream.available(); 

                       bufferSize = Math.min(bytesAvailable, maxBufferSize);
                       buffer = new byte[bufferSize];

                       // read file and write it into form...
                       bytesRead = fileInputStream.read(buffer, 0, bufferSize);  

                       while (bytesRead > 0) {

                         dos.write(buffer, 0, bufferSize);
                         bytesAvailable = fileInputStream.available();
                         bufferSize = Math.min(bytesAvailable, maxBufferSize);
                         bytesRead = fileInputStream.read(buffer, 0, bufferSize);   

                        }

                       // send multipart form data necesssary after file data...
                       dos.writeBytes(lineEnd);
                       dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

                       // Responses from the server (code and message)
                       serverResponseCode = conn.getResponseCode();
                       final String serverResponseMessage = conn.getResponseMessage();

                       Log.i("uploadFile", "HTTP Response is : " 
                               + serverResponseMessage + ": " + serverResponseCode);

                       //server responsecode 200 means upload successful
                       if(serverResponseCode == 200){

                           runOnUiThread(new Runnable() {
                                public void run() {

                                    String msg = serverResponseMessage  + "File Upload Completed.\n\n "

                                                  +fileName;

                                    messageText.setText(msg);

                                    Boolean isDel =  sourceFile.delete();

                                    if(isDel)
                                    {
                                    Toast.makeText(MathsGameResults.this, "File Upload Complete. And Deleted.", 
                                                 Toast.LENGTH_SHORT).show();
                                    }
                                    else
                                    {
                                        Toast.makeText(MathsGameResults.this, "File Upload Complete. And NOT Deleted.", 
                                                     Toast.LENGTH_SHORT).show();
                                        }
                                }
                            });                
                       }    

                       //close the streams //
                       fileInputStream.close();
                       dos.flush();
                       dos.close();

                  } catch (MalformedURLException ex) {

                      dialog.dismiss();  
                      ex.printStackTrace();

                      runOnUiThread(new Runnable() {
                          public void run() {
                              messageText.setText("MalformedURLException Exception : check script url.");
                              Toast.makeText(MathsGameResults.this, "MalformedURLException", Toast.LENGTH_SHORT).show();
                          }
                      });

                      Log.e("Upload file to server", "error: " + ex.getMessage(), ex);  
                  } catch (Exception e) {

                      dialog.dismiss();  
                      e.printStackTrace();

                      final String d =  e.getMessage() + " " + e.getStackTrace();

                      runOnUiThread(new Runnable() {
                          public void run() {
                              messageText.setText(d + " Got Exception : see logcat ");
                              Toast.makeText(MathsGameResults.this, "Got Exception : see logcat ", 
                                      Toast.LENGTH_LONG).show();
                          }
                      });
                      Log.e("Upload file to server Exception", "Exception : " 
                                                       + e.getMessage(), e);  
                  }
                  dialog.dismiss();       
                  return serverResponseCode; 

               } // End else block 
             } 

路径是保存文件并创建文件名:

/**
     * Method used to save Raw data to a file on phone
     * 
     * @param data
     */
    public void writeToFileRawData(String data) {

        // creating the file where the contents will be written to
        File file = new File(dir, fileNameRaw + ".txt");

        FileOutputStream os;

        try {

            boolean append = true;

            os = new FileOutputStream(file, append);

            String writeMe = data + "\n";

            if (isHeaderDateRaw) {
                os.write(headerDateRaw.getBytes());
                isHeaderDateRaw = false;
            }

            if (isHeaderRawValues) {
                os.write(headerRawValues.getBytes());
                isHeaderRawValues = false;
            }

            os.write(writeMe.getBytes());

            os.close();
        } catch (FileNotFoundException e) {

            e.printStackTrace();
        } catch (IOException e) {

            e.printStackTrace();
        }

    }

使用处理程序将数据保存到文件:

    // code relating to saving to file
            File sdCard = Environment.getExternalStorageDirectory();
            dir = new File(sdCard.getAbsolutePath() + "/files/");
            dir.mkdir();
//creating file name
fileNameRaw = "MathsGame-Raw-" + timestamp + android.os.Build.SERIAL;

通过意图将文件名传递给下一个活动:

case TGDevice.MSG_RAW_DATA:

                headerRawValues = order("Seconds") + order("Value") + "\n";

                Time time2= new Time();
                time2.setToNow();

                String seconds2 = time2.hour + ":" + (time2.minute < 10 ? "0"+time2.minute : time2.minute) + ":"
                        + (time2.second < 10 ? "0"+time2.second : time2.second);


                // creating the string to be written to file
                String line2 = order(seconds2 + "") + order("" + msg.arg1)
                        + "\n";

                // write the string to file
                writeToFileRawData(line2);

                break;

0 个答案:

没有答案