2016-09-20 9 views
0

기본적으로 mkdir을 사용하여 폴더를 만든 다음 해당 폴더에 간단한 텍스트 파일을 작성합니다. 마지막 단계로 MediaScannerConnection.ScanFile을 사용하여 파일 탐색기에 표시되도록합니다.Android API 23 mkdir 만들어진 폴더는 Windows 탐색기에서 단일 파일로 표시됩니다.

내 안드로이드 폰의 파일 탐색기에서 폴더와 텍스트 파일을 모두 볼 수 있습니다. MTP를 사용하여 USB를 통해 내 Windows 10 컴퓨터에 전화를 연결할 때 다른 모든 폴더가 표시되지만 새로 생성 된 폴더는 단일 파일, 확장자 없음, 4KB 크기.

스마트 폰과 컴퓨터를 다시 시작해도 문제가 해결되지 않지만 내 안드로이드 파일 탐색기에서 폴더의 이름을 변경 한 다음 휴대 전화를 다시 시작하면 Windows 탐색기의 일반 폴더로 표시됩니다.

버튼을 클릭하고 덮어 쓰기를 선택할 파일 목록이있는 대화 상자와 새로운 파일 이름을 입력하기위한 편집 문구, 음수 버튼 및 양수 버튼이 표시됩니다. 여기

코드 :

/* 
Save Config in a File stored in interal storage --> which is emulated as external storage 0 
Shows a Dialog window with the option to select a file which is already there or type in a name for a new file or choose from a list of files 
--> save the new file or cancel the dialog 
*/ 
public void savebutton(View view) { 

     try { 
      // Instantiate an AlertDialog with application context this 
      AlertDialog.Builder builder = new AlertDialog.Builder(this); 
      //External Storage storage/emulated/0/Config --> storage/emulated/0 is internal storage emulated as sd-card 
      dir = new File(Environment.getExternalStorageDirectory() + folder); 
      if (!dir.exists()) { 
       if (!dir.mkdir()) { //create directory if not existing yet 
        Log.d(MainActivity.LOG_TAG, "savebutton: directory was not created"); 
       } 
      } 

      //set title of dialog 
      builder.setTitle("Save Configuration in Text File"); 
      //Add edittext to dialog 
      final EditText input = new EditText(ConfigActivity.this); 
      LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
        LinearLayout.LayoutParams.MATCH_PARENT, 
        LinearLayout.LayoutParams.MATCH_PARENT); 
      input.setLayoutParams(lp); 
      input.setImeOptions(EditorInfo.IME_ACTION_DONE);  // instead of a RETURN button you get a DONE button 
      input.setSingleLine(true);        // single line cause more lines would change the layout 
      java.util.Calendar c = java.util.Calendar.getInstance(); 
      int day = c.get(java.util.Calendar.DAY_OF_MONTH); 
      int month = c.get(java.util.Calendar.MONTH) + 1; 
      int year = c.get(java.util.Calendar.YEAR); 
      String date = Integer.toString(day) + "." + Integer.toString(month) + "." + Integer.toString(year); 
      String savename = name + "-" + date; 
      input.setText(savename); 

      //Append term + "=" + value --> like LevelOn=50 
      for (int itemcounter = 0; itemcounter < value.length; itemcounter++) 
       datastring += (term[itemcounter] + "=" + getvalue(itemcounter) + "\n"); 

      //File List of already stored files for dialog 
      mFilelist = dir.list(); 
      builder.setItems(mFilelist, new DialogInterface.OnClickListener() { 
       public void onClick(DialogInterface dialog, int which) { 

        mChosenFile = mFilelist[which]; // the item/file which was selected in the file list 

        try { 
         //Create text file in directory /Pump Config Files 
         File file = new File(dir.getAbsolutePath(), mChosenFile); 
         //create bufferedwrite with filewriter 
         BufferedWriter bw = new BufferedWriter(new FileWriter(file)); 
         //write to file --> an existing file will be overwritten 
         bw.write(datastring); 
         //Flush bufferedwriter 
         bw.close(); 
         //LOG 
         System.out.println("Wrote to file"); 
         //Show a message 
         Toast.makeText(getApplicationContext(), "Saved data", Toast.LENGTH_SHORT).show(); 

         // initiate media scan -->cause sometimes created files are nt shown on computer when connected to phone via USB 
         // restarting the smartphone or rename folder can help too 
         // make the scanner aware of the location and the files you want to see 
         MediaScannerConnection.scanFile(
           getApplicationContext(), 
           new String[]{dir.getAbsolutePath()}, 
           null, 
           new MediaScannerConnection.OnScanCompletedListener() { 
            @Override 
            public void onScanCompleted(String path, Uri uri) { 
             Log.v("LOG", "file " + path + " was scanned successfully: " + uri); 
            } 
           }); 
        } catch (Exception e) { 
         System.out.print(e.toString()); 
        } 
        //dismissing the dialog 
        dialog.cancel(); 
        dialog.dismiss(); 
       } 
      }); 

      // Get the AlertDialog from builder create() 
      AlertDialog dialog = builder.create(); 
      //Set dialog view/layout 
      dialog.setView(input); 

      //Add positive button to dialog 
      //When pressing the positive button a file with the specified name and configurtion is stored on internal storage 
      dialog.setButton(DialogInterface.BUTTON_POSITIVE, "Save", new DialogInterface.OnClickListener() { 
       public void onClick(DialogInterface dialog, int which) { 
        try { 
         filename = input.getText().toString(); 
         //Create text file in directory /Pump Config Files 
         File file = new File(dir.getAbsolutePath(), filename + ".txt"); 
         //create bufferedwrite with filewriter 
         BufferedWriter bw = new BufferedWriter(new FileWriter(file)); 
         //write to file --> an existing file will be overwritten 
         bw.write(datastring); 
         //Flush bufferedwriter 
         bw.close(); 
         //LOG 
         System.out.println("Wrote to file"); 
         //Show a message 
         Toast.makeText(getApplicationContext(), "Saved data", Toast.LENGTH_SHORT).show(); 
        } catch (Exception e) { 
         System.out.print(e.toString()); 
        } 
        // initiate media scan -->cause sometimes created files are nt shown on computer when connected to phone via USB 
        // restarting the smartphone or rename folder can help too 
        // make the scanner aware of the location and the files you want to see 
        MediaScannerConnection.scanFile(
          getApplicationContext(), 
          new String[]{dir.getAbsolutePath()}, 
          null, 
          new MediaScannerConnection.OnScanCompletedListener() { 
           @Override 
           public void onScanCompleted(String path, Uri uri) { 
            Log.v("LOG", "file " + path + " was scanned successfully: " + uri); 
           } 
          }); 

        dialog.cancel(); 
        dialog.dismiss(); 
       } 
      }); 

      //Add negative button 
      dialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() { 
       public void onClick(DialogInterface dialog, int which) { 
        dialog.cancel(); 
       } 
      }); 
      //show the save dialog 
      dialog.show(); 
     } catch (Exception e) { 
      System.out.print(e.toString()); 
     } 
    } 

안드로이드 API (23)와 API (21) 작품 (21)에 미세하지만 23

+0

'Log.d (MainActivity.LOG_TAG, "savebutton : 디렉토리가 생성되지 않았습니다");'. 그 진술 다음에 return 문을 잊어 버렸습니다. – greenapps

+0

'new String [] {dir.getAbsolutePath()},'. 대신에 파일을 스캔해야합니다 :'new String [] {file.getAbsolutePath()},'. – greenapps

답변

0

감사 greenapps에에서 테스트,

새로운 String [] { dir.getAbsolutePath()} ,. 대신 파일을 검사해야합니다. new String [] {file.getAbsolutePath()},

잘 작동합니다.

나는 이와 같은 작은 세부 사항이 항상 누락되었습니다.