简体   繁体   中英

Local html file always results to java.io.FileNotFoundException: open failed: ENOENT (No such file or directory)

I have a browser type application that you can edit html, css and js files in it. I can open the code and save them. With html files, I have a preview feature that whatever change you did on the html file, you can preview it on a WebView.

This is the logcat error I receive whenever I try to preview html files:

08-10 10:48:12.283: E/EditorPreviewActivity(4109): ファイル出力に失敗しました。java.io.FileNotFoundException: : open failed: ENOENT (No such file or directory)
08-10 10:48:12.284: D/AndroidRuntime(4109): Shutting down VM
08-10 10:48:12.284: D/AndroidRuntime(4109): --------- beginning of crash
08-10 10:48:12.287: E/AndroidRuntime(4109): FATAL EXCEPTION: main
08-10 10:48:12.287: E/AndroidRuntime(4109): Process: com.corundumPro, PID: 4109
08-10 10:48:12.287: E/AndroidRuntime(4109): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.corundumPro/com.corundumPro.features.editor.EditorPreviewActivity}: com.corundumPro.common.exception.ArcRuntimeException: com.corundumPro.common.exception.ArcAppException: java.io.FileNotFoundException: : open failed: ENOENT (No such file or directory)
08-10 10:48:12.287: E/AndroidRuntime(4109):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
08-10 10:48:12.287: E/AndroidRuntime(4109):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
08-10 10:48:12.287: E/AndroidRuntime(4109):     at android.app.ActivityThread.access$800(ActivityThread.java:151)
08-10 10:48:12.287: E/AndroidRuntime(4109):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
08-10 10:48:12.287: E/AndroidRuntime(4109):     at android.os.Handler.dispatchMessage(Handler.java:102)
08-10 10:48:12.287: E/AndroidRuntime(4109):     at android.os.Looper.loop(Looper.java:135)
08-10 10:48:12.287: E/AndroidRuntime(4109):     at android.app.ActivityThread.main(ActivityThread.java:5254)
08-10 10:48:12.287: E/AndroidRuntime(4109):     at java.lang.reflect.Method.invoke(Native Method)
08-10 10:48:12.287: E/AndroidRuntime(4109):     at java.lang.reflect.Method.invoke(Method.java:372)
08-10 10:48:12.287: E/AndroidRuntime(4109):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
08-10 10:48:12.287: E/AndroidRuntime(4109):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
08-10 10:48:12.287: E/AndroidRuntime(4109): Caused by: com.corundumPro.common.exception.ArcRuntimeException: com.corundumPro.common.exception.ArcAppException: java.io.FileNotFoundException: : open failed: ENOENT (No such file or directory)
08-10 10:48:12.287: E/AndroidRuntime(4109):     at com.corundumPro.features.editor.EditorPreviewActivity.onCreate(EditorPreviewActivity.java:143)
08-10 10:48:12.287: E/AndroidRuntime(4109):     at android.app.Activity.performCreate(Activity.java:5990)
08-10 10:48:12.287: E/AndroidRuntime(4109):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
08-10 10:48:12.287: E/AndroidRuntime(4109):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
08-10 10:48:12.287: E/AndroidRuntime(4109):     ... 10 more
08-10 10:48:12.287: E/AndroidRuntime(4109): Caused by: com.corundumPro.common.exception.ArcAppException: java.io.FileNotFoundException: : open failed: ENOENT (No such file or directory)
08-10 10:48:12.287: E/AndroidRuntime(4109):     at com.corundumPro.common.function.FileFunction.writeFile(FileFunction.java:61)
08-10 10:48:12.287: E/AndroidRuntime(4109):     at com.corundumPro.common.function.FileFunction.makeTemporaryFile(FileFunction.java:91)
08-10 10:48:12.287: E/AndroidRuntime(4109):     at com.corundumPro.features.editor.EditorPreviewActivity.onCreate(EditorPreviewActivity.java:138)
08-10 10:48:12.287: E/AndroidRuntime(4109):     ... 13 more
08-10 10:48:12.287: E/AndroidRuntime(4109): Caused by: java.io.FileNotFoundException: : open failed: ENOENT (No such file or directory)
08-10 10:48:12.287: E/AndroidRuntime(4109):     at libcore.io.IoBridge.open(IoBridge.java:456)
08-10 10:48:12.287: E/AndroidRuntime(4109):     at java.io.FileOutputStream.<init>(FileOutputStream.java:87)
08-10 10:48:12.287: E/AndroidRuntime(4109):     at java.io.FileOutputStream.<init>(FileOutputStream.java:72)
08-10 10:48:12.287: E/AndroidRuntime(4109):     at java.io.FileWriter.<init>(FileWriter.java:80)
08-10 10:48:12.287: E/AndroidRuntime(4109):     at com.corundumPro.common.function.FileFunction.writeFile(FileFunction.java:47)
08-10 10:48:12.287: E/AndroidRuntime(4109):     ... 15 more
08-10 10:48:12.287: E/AndroidRuntime(4109): Caused by: android.system.ErrnoException: open failed: ENOENT (No such file or directory)
08-10 10:48:12.287: E/AndroidRuntime(4109):     at libcore.io.Posix.open(Native Method)
08-10 10:48:12.287: E/AndroidRuntime(4109):     at libcore.io.BlockGuardOs.open(BlockGuardOs.java:186)
08-10 10:48:12.287: E/AndroidRuntime(4109):     at libcore.io.IoBridge.open(IoBridge.java:442)
08-10 10:48:12.287: E/AndroidRuntime(4109):     ... 19 more

This is the EditorPreviewActivity.java code:

public class EditorPreviewActivity extends BaseActivity {
    static final String TAG = "EditorPreviewActivity";

    /** URLバー */
    private LinearLayout editorPreviewLinearLayout1;

    /** URL入力エディットボックス */
    private EditText editorPreviewEditText1;

    /** リロードボタン */
    private ImageButton editorPreviewImageButton1;

    /** WEB表示 */
    private EditorPreviewWebView editorPreviewWebView1;

    /** ツールバー */
    private LinearLayout editorPreviewLinearLayout2;

    /** ホームボタン */
    private ImageButton editorPreviewImageButton2;

    /** Prevボタン */
    private ImageButton editorPreviewImageButton3;

    /** Nextボタン */
    private ImageButton editorPreviewImageButton4;

    /** リロードボタン */
    private ImageButton editorPreviewImageButton5;

    /** キャンセルボタン */
    private ImageButton editorPreviewImageButton6;

    /** プログレス */
    private ProgressBar editorPreviewProgressBar1;

    /** オプションメニューボタン */
    private ImageButton editorPreviewImageButton7;

    /** グラスペイン */
    GlassPaneLayout editorPreviewGlassPane1;

    /** Webモードファンクション */
    private WebModeFunction webModeFunction = new WebModeFunction();

    /** プレビュー用ファイルパス */
    private String previewFilePath = "";

    /** 選択されたWebモード */
    private int selectedWebMode = -1;

    /**
     * 作成処理
     * <p>
     * onCreate()のオーバーライド<br>
     * アクティビティ生成時にコールされる。
     * </p>
     * @param bundle バンドル
     */
    @Override
    public void onCreate(Bundle bundle) {
        LogUtil.d(TAG, "[IN ] onCreate()");

        super.onCreate(bundle);

        // タイトル非表示
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        // 画面のフォーカスを外す
        this.getWindow().setSoftInputMode(LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

        // Viewにレイアウト設定
        setContentView(R.layout.editor_preview);

        // View初期化
        initViews();

        // ファイルパス取得
        String filePath = getIntent().getStringExtra(SystemInfo.KEY_EDITOR_PREVIEW_URL);
        LogUtil.d(TAG, "filePath:" + filePath);

        // コンテンツ取得
        String contents = getIntent().getStringExtra(SystemInfo.KEY_EDITOR_PREVIEW_CONTENTS);

        // 選択されたWebモード取得
        this.selectedWebMode = getIntent().getIntExtra(SystemInfo.KEY_SELECTED_WEB_MODE, DBAdapter.WEB_MODE_OPERATION);
        LogUtil.d(TAG, "selectedWebMode:" + String.valueOf(selectedWebMode));

        // プレビュー用に一時ファイルを作成する
        FileFunction fileFunction = new FileFunction();
        try {
            this.previewFilePath = fileFunction.makeTemporaryFile(filePath, contents);
            LogUtil.d(TAG, "previewFilePath:" + String.valueOf(previewFilePath));

        } catch (ArcAppException e) {
            LogUtil.e(TAG, getString(e.getResourceId()) + e.getMessage());
            throw new ArcRuntimeException(e);
        }

        LogUtil.d(TAG, "[OUT] onCreate()");
    }

    /**
     * レジューム処理
     * <p>
     * onResume()のオーバーライド<br>
     * アクティビティ再開時にコールされる。
     * </p>
     */
    @Override
    public void onResume() {
        LogUtil.d(TAG, "[IN ] onResume()");
        super.onResume();

        // 選択されたWebモードを設定
        webModeFunction.setWebMode(selectedWebMode);

        // 画面表示設定
        String filePathWithProtocol = Const.PROTOCOL_FILE + previewFilePath;
        editorPreviewEditText1.setText(filePathWithProtocol);   // URL設定
        editorPreviewLinearLayout1.setVisibility(webModeFunction.getVisibleUrlBar());   // URLバー表示設定
        editorPreviewLinearLayout2.setVisibility(webModeFunction.getVisileToolBar());   // ツールバー表示設定
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN
                            ,webModeFunction.getVisibleStatusBar());                    // フルスクリーン表示設定


        // WebView更新
        refreshWebview(StringUtil.nvl(filePathWithProtocol, ""));

        LogUtil.d(TAG, "[OUT] onResume()");
    }

    /**
     * フラグメントレジューム処理
     * <p>
     * onResumeFragments()のオーバーライド<br>
     * アクティビティ表示時にコールされる。
     * </p>
     */
    @Override
    public void onResumeFragments() {
        LogUtil.d(TAG, "[IN ] onResumeFragments()");
        super.onResumeFragments();
        LogUtil.d(TAG, "[OUT] onResumeFragments()");
    }

    /**
     * 一時停止処理
     * <p>
     * onPause()のオーバーライド<br>
     * アクティビティ一時停止時にコールされる。
     * </p>
     */
    @Override
    public void onPause() {
        LogUtil.d(TAG, "[IN ] onPause()");
        super.onPause();
        LogUtil.d(TAG, "[OUT] onPause()");
    }

    /**
     * 停止処理
     * <p>
     * onStop()のオーバーライド<br>
     * アクティビティ停止時にコールされる。
     * </p>
     */
    @Override
    public void onStop() {
        LogUtil.d(TAG, "[IN ] onStop()");
        super.onStop();
        LogUtil.d(TAG, "[OUT] onStop()");
    }

    /**
     * 終了処理
     * <p>
     * onDestroy()のオーバーライド<br>
     * アクティビティ終了時にコールされる。
     * </p>
     */
    @Override
    public void onDestroy() {
        LogUtil.d(TAG, "[IN ] onDestroy()");
        super.onDestroy();

        // プレビュー用一時ファイルを削除
        if (!FileUtils.deleteQuietly(new File(previewFilePath)) ) {
            LogUtil.w(TAG, getString(R.string.log_err_delete_file) + ":" + previewFilePath);
        }
        LogUtil.d(TAG, "[OUT] onDestroy()");
    }

    /**
     * View初期化処理
     * <p>
     * Viewの初期化を行う。
     * </p>
     */
    @SuppressLint("SetJavaScriptEnabled")
    protected void initViews() {
        LogUtil.d(TAG, "[IN ] initViews()");

        /* 上部URLバー */
        editorPreviewLinearLayout1 = (LinearLayout)findViewById(R.id.editor_preview_LinearLayout1);

        /* URL入力エディットボックス */
        editorPreviewEditText1 = (EditText)findViewById(R.id.editor_preview_editText1);

        /* リロードボタン */
        editorPreviewImageButton1 = (ImageButton)findViewById(R.id.editor_preview_imageButton1);
        editorPreviewImageButton1.setEnabled(true);

        // WEB表示設定
        editorPreviewWebView1 = (EditorPreviewWebView)findViewById(R.id.editor_preview_webView1);
        editorPreviewWebView1.requestFocus();
        editorPreviewWebView1.getSettings().setJavaScriptEnabled(true);
        editorPreviewWebView1.getSettings().setDomStorageEnabled(true);
        editorPreviewWebView1.getSettings().setUseWideViewPort(true);
        editorPreviewWebView1.getSettings().setLoadWithOverviewMode(true);

        editorPreviewWebView1.setWebViewClient(new WebViewClient() {
            /**
             * ページ読み込み開始処理
             */
            @Override
            public void onPageStarted(WebView webView, String url, Bitmap favicon) {
                super.onPageStarted(webView, url, favicon);
                LogUtil.d(TAG, "[IN ] onPageStarted()");
                LogUtil.d(TAG, "url:" + url);

                // ツールバー表示初期化
                initToolBar(webModeFunction.getVisileToolBar());

                LogUtil.d(TAG, "[OUT] onPageStarted()");
            }

            /**
             * ページ読み込み完了処理
             */
            @Override
            public void onPageFinished(WebView webView, String url) {
                super.onPageFinished(webView, url);
                LogUtil.d(TAG, "[IN ] onPageFinished()");
                LogUtil.d(TAG, "url:" + url);

                // ツールバー表示
                showToolBar(webModeFunction.getVisileToolBar());

                LogUtil.d(TAG, "[OUT] onPageFinished()");
            }

            /**
             * リダイレクト処理
             */
            public boolean shouldOverrideUrlLoading(WebView webView, String url) {
                LogUtil.d(TAG, "[IN ] shouldOverrideUrlLoading()");
                LogUtil.d(TAG, "url:" + url);
                LogUtil.d(TAG, "return true");
                LogUtil.d(TAG, "[OUT] shouldOverrideUrlLoading()");
                return true;
            }
        });

        /* ツールバー */
        editorPreviewLinearLayout2 = (LinearLayout) findViewById(R.id.editor_preview_LinearLayout2);

        /* ホームボタン */
        editorPreviewImageButton2 = (ImageButton) findViewById(R.id.editor_preview_imageButton2);

        /* Prevボタン */
        editorPreviewImageButton3 = (ImageButton) findViewById(R.id.editor_preview_imageButton3);

        /* Nextボタン */
        editorPreviewImageButton4 = (ImageButton) findViewById(R.id.editor_preview_imageButton4);

        /* リロードボタン */
        editorPreviewImageButton5 = (ImageButton) findViewById(R.id.editor_preview_imageButton5);

        /* キャンセルボタン */
        editorPreviewImageButton6 = (ImageButton) findViewById(R.id.editor_preview_imageButton6);

        /* プログレス */
        editorPreviewProgressBar1 = (ProgressBar) findViewById(R.id.editor_preview_progressBar1);

        /* オプションメニューボタン */
        editorPreviewImageButton7 = (ImageButton) findViewById(R.id.editor_preview_imageButton7);

        /** グラスペイン */
        editorPreviewGlassPane1 = (GlassPaneLayout)this.findViewById(R.id.editor_preview_glass_pane1);
        editorPreviewGlassPane1.setOnTouchListener(glassPaneListener);

        LogUtil.d(TAG, "[OUT] initViews()");
    }

    /**
     * WebView更新処理
     * <p>
     * WebViewの更新を行う。
     * </p>
     * @param url URL
     */
    protected void refreshWebview(String url) {
        LogUtil.d(TAG, "[IN ] refreshWebview()");
        LogUtil.d(TAG, "url:" + url);

        // WebView更新
        editorPreviewWebView1.loadUrl(url);

        LogUtil.d(TAG, "[OUT] refreshWebview()");
    }

    /**
     * ツールバー表示初期化<br>
     *
     * @param visible 表示可:View.VISIBLE, 表示不可:View.GONE
     */
    protected void initToolBar(int visible) {
        LogUtil.d(TAG, "[IN ] initToolBar()");

        if (visible == View.VISIBLE) {
            // ホームボタン
            editorPreviewImageButton2.setEnabled(true);
            // Prevボタン
            editorPreviewImageButton3.setEnabled(false);
            // Nextボタン
            editorPreviewImageButton4.setEnabled(false);
            // リロードボタン
            editorPreviewImageButton5.setEnabled(true);
            // キャンセルボタン
            editorPreviewImageButton6.setEnabled(true);
            // オプションメニューボタン
            editorPreviewImageButton7.setEnabled(true);
            // プログレス
            editorPreviewProgressBar1.setVisibility(View.VISIBLE);
        }
        LogUtil.d(TAG, "[OUT] initToolBar()");
    }

    /**
     * ツールバー表示<br>
     *
     * @param visible 表示可:View.VISIBLE, 表示不可:View.GONE
     */
    protected void showToolBar(int visible) {
        LogUtil.d(TAG, "[IN ] showToolBar()");

        if (visible == View.VISIBLE) {
            // ホームボタン
            editorPreviewImageButton2.setEnabled(true);
            // Prevボタン
            editorPreviewImageButton3.setEnabled(editorPreviewWebView1.canGoBack());
            // Nextボタン
            editorPreviewImageButton4.setEnabled(editorPreviewWebView1.canGoForward());
            // リロードボタン
            editorPreviewImageButton5.setEnabled(true);
            // キャンセルボタン
            editorPreviewImageButton6.setEnabled(false);
            // オプションメニューボタン
            editorPreviewImageButton7.setEnabled(true);
            // プログレス非表示
            editorPreviewProgressBar1.setVisibility(View.GONE);

        }
        LogUtil.d(TAG, "[OUT] showToolBar()");
    }

    /**
     * GlassPaneタッチリスナ処理
     * <p>
     * GlassPaneがタッチされた時にコールされる。<br>
     * </p>
     */
    private View.OnTouchListener glassPaneListener = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View view, MotionEvent event) {
            LogUtil.d(TAG, "[IN ] glassPaneListener::onTouch()");
            view.performClick();
            finish();
            LogUtil.d(TAG, "[OUT] glassPaneListener::onTouch()");
            return true;
        }
    };
}

This is the FileFunction.java code:

public class FileFunction {
    static final String TAG = "FileFunction";

    /**
     * コンストラクタ<br>
     *
     */
    public FileFunction() {
        LogUtil.d(TAG, "[IN ] FileFunction()");
        LogUtil.d(TAG, "[OUT] FileFunction()");
    }

    /**
     * ファイルに書き込みます。<br>
     *
     * @param filePath ファイルパス
     * @param contents コンテンツ
     * @throw ArcAppException アプリケーション例外
     */
    public void writeFile(String filePath, String contents) throws ArcAppException {
        LogUtil.d(TAG, "[IN ] writeFile()");
        LogUtil.d(TAG, "filePath:" + filePath);

        FileWriter fileWriter = null;

        try {
            fileWriter = new FileWriter(filePath);

            /* ファイル書き込み */
            fileWriter.write(contents);
            fileWriter.close();

        } catch (Exception e) {
            if (null != fileWriter) {
                try {
                    fileWriter.close();
                } catch (Exception e1) {
                    throw new ArcAppException(R.string.log_err_close_file, e1);
                }
            }
            throw new ArcAppException(R.string.log_err_write_file, e);
        } finally {
            LogUtil.d(TAG, "[OUT] writeFile()");
        }
    }

    /**
     * 一時ファイルを作成します。
     *
     * @param filePath ファイルパス
     * @param contents コンテンツ
     * @throws ArcAppException アプリケーション例外
     */
    public String makeTemporaryFile(String filePath, String contents) throws ArcAppException {
        LogUtil.d(TAG, "[IN ] makeTemporaryFile()");

        // プレビュー用に一時ファイルを保存する
        String tempFilePath = "";
        for (int i = 0; i < EnvUtil.getRetry(); i++) {
            tempFilePath = FileUtil.getTemporaryFileName(filePath);
            if (new File(tempFilePath).exists()) {
                continue;
            } else {
                break;
            }
        }
        LogUtil.d(TAG, "tempFilePath:" + String.valueOf(tempFilePath));

        try {
            // ファイルを保存する
            this.writeFile(tempFilePath, contents);

        } catch (ArcAppException e) {
            throw e;

        } finally {
            LogUtil.d(TAG, "[OUT] makeTemporaryFile()");
        }
        return tempFilePath;
    }
}

and here is the FileUtil.java code:

public class FileUtil {
    static final String TAG = "FileUtil";



    /**
     * デフォルトコンストラクタ.
     */
    private FileUtil() {
    }

    /**
     * ベースフォルダパス取得処理
     * <p>
     * SDカード上のコランダムフォルダのパスを取得する。
     * </p>
     * @param context コンテキスト
     * @return SDカード上のコランダムフォルダパス
     */
    public static String getBaseDirPath(Context context) {
        LogUtil.d(TAG, "[IN ] getBaseDirPath()");

        String path = Environment.getExternalStorageDirectory() + "/" + context.getResources().getString(R.string.app_name);

        LogUtil.d(TAG, "path:" + path);
        LogUtil.d(TAG, "[OUT] getBaseDirPath()");
        return path;
    }

    /**
     * ファイル種別変換処理
     * <p>
     * ファイルリストで使用する「ファイル種別」への変換を行う。
     * </p>
     * @param file ファイルオブジェクト
     * @return ファイル種別
     */
    public static int convertFileType(File file) {
        LogUtil.d(TAG, "[IN ] convertFileType()");
        LogUtil.d(TAG, "file:" + file.getPath());

        int fileType = FileListInfo.FILE_TYPE_OTHER;

        /* ファイル種別:フォルダ */
        if (true == file.isDirectory()) {
            fileType = FileListInfo.FILE_TYPE_DIR;

        /* ファイル種別:画像 */
        } else if ((file.getName().endsWith(".jpg"))
                || (file.getName().endsWith(".JPG"))
                || (file.getName().endsWith(".jpeg"))
                || (file.getName().endsWith(".JPEG"))
                || (file.getName().endsWith(".png"))
                || (file.getName().endsWith(".PNG"))
                || (file.getName().endsWith(".gif"))
                || (file.getName().endsWith(".GIF"))) {
            fileType = FileListInfo.FILE_TYPE_IMAGE;

        /* ファイル種別:編集可能ファイル */
        } else if ((file.getName().endsWith(".js"))
                || (file.getName().endsWith(".JS"))
                || (file.getName().endsWith(".css"))
                || (file.getName().endsWith(".CSS"))
                || (file.getName().endsWith(".html"))
                || (file.getName().endsWith(".HTML"))
                || (file.getName().endsWith(".xml"))
                || (file.getName().endsWith(".XML"))
                || (file.getName().endsWith(".txt"))
                || (file.getName().endsWith(".TXT"))
                || (-1 == file.getName().lastIndexOf("."))) {
            fileType = FileListInfo.FILE_TYPE_EDIT_ABLE;

        /* ファイル種別:編集不可能ファイル */
        } else {
            fileType = FileListInfo.FILE_TYPE_OTHER;
        }

        LogUtil.d(TAG, "fileType:" + fileType);
        LogUtil.d(TAG, "[OUT] convertFileType()");
        return fileType;
    }

    /**
     * ファイルサイズ変換処理
     * <p>
     * ファイルリストで使用する「ファイルサイズ」に変換を行う。
     * </p>
     * @param size ファイルサイズ
     * @return 表示用のファイルサイズ文字列
     */
    public static String convertSize(long size) {
        LogUtil.d(TAG, "[IN ] convertSize()");
        LogUtil.d(TAG, "size:" + size);

        float tmp = 0;
        String fileSize = "";
        long GByte = 1000 * 1000 * 1000;
        long MByte = 1000 * 1000;
        long KByte = 1000;

        if (size >= GByte) {
            /* ギガバイト表示 */
            tmp = (float)size / GByte;
            fileSize = tmp + " GByte";
        } else if (size >= MByte) {
            /* メガバイト表示 */
            tmp = (float)size / MByte;
            fileSize = tmp + " MByte";
        } else if (size >= KByte) {
            /* キロバイト表示 */
            tmp = (float)size / KByte;
            fileSize = tmp + " KByte";
        } else {
            /* バイト表示 */
            tmp = (float)size;
            fileSize = tmp + " Byte";
        }

        LogUtil.d(TAG, "fileSize:" + fileSize);
        LogUtil.d(TAG, "[OUT] convertSize()");
        return fileSize;
    }

    /**
     * ファイル強制削除処理
     * <p>
     * ファイルの強制削除を行う。<br>
     * フォルダの場合、配下のファイルも全て削除する。
     * </p>
     * @param file ファイル
s    */
    public static void deleteForce(File file){
        LogUtil.d(TAG, "[IN ] deleteForce()");
        LogUtil.d(TAG, "file:" + file.getPath());

        /* ファイルが存在しない */
        if (false == file.exists()) {
            LogUtil.d(TAG, "[OUT] deleteForce()");
            return ;
        }

        /* ファイル削除 */
        if (true == file.isFile()) {
            try {
                boolean ret = file.delete();
                LogUtil.d(TAG, "ret:" + ret);
            } catch (Exception e) {
                LogUtil.d(TAG, e.getMessage());
            }
        }

        /* フォルダの場合、配下のファイルを再帰的に削除 */
        if (true == file.isDirectory()) {
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++) {
                deleteForce( files[i] );
            }

            try {
                boolean ret = file.delete();
                LogUtil.d(TAG, "ret:" + ret);
            } catch (Exception e) {
                LogUtil.d(TAG, e.getMessage());
            }
        }

        LogUtil.d(TAG, "[OUT] deleteForce()");
    }

    /**
     * 最後の名前区切り文字の位置を取得します。<br>
     *
     * @param filename
     * @return 最後の名前区切り文字位置
     */
    public static int indexOfLastSeparator(String filename) {
        if (filename == null) {
            return -1;
        }
        int lastUnixPos = filename.lastIndexOf(Const.SEPARATOR_SLASH);
        int lastWindowsPos = filename.lastIndexOf(Const.SEPARATOR_YEN);
        return Math.max(lastUnixPos, lastWindowsPos);
    }

    /**
     * 拡張子区切り文字の位置を取得します。<br>
     *
     * @param filename
     * @return 拡張子区切り文字位置
     */
    public static int indexOfExtension(String filename) {
        if (filename == null) {
            return -1;
        }
        int extensionPos = filename.lastIndexOf(Const.SEPARATOR_EXTENSION);
        int lastSeparator = indexOfLastSeparator(filename);
        return (lastSeparator > extensionPos ? -1 : extensionPos);
    }

    /**
     * 拡張子を取得します。<br>
     *
     * @param filename
     * @return 拡張子
     */
    public static String getExtension(String filename) {
        if (filename == null) {
            return null;
        }
        int index = indexOfExtension(filename);
        if (index == -1) {
            return "";
        } else {
            return filename.substring(index + 1);
        }
    }

    /**
     * ファイル名(拡張子あり)を取得します。<br>
     *
     * @param filename
     * @return ファイル名(拡張子あり)
     */
    public static String getName(String filename) {
        if (filename == null) {
            return null;
        }
        int index = indexOfLastSeparator(filename);
        return filename.substring(index + 1);
    }

    /**
     * ファイルパスから拡張子を取り除きます。<br>
     *
     * @param filename
     * @return 拡張子を取り除いたファイルパス
     */
    public static String removeExtension(String filename) {
        if (filename == null) {
            return null;
        }
        int index = indexOfExtension(filename);
        if (index == -1) {
            return filename;
        } else {
            return filename.substring(0, index);
        }
    }

    /**
     * ファイル名(拡張子なし)を取得します。<br>
     *
     * @param filename
     * @return ファイル名(拡張子なし)
     */
    public static String getBaseName(String filename) {
        return removeExtension(getName(filename));
    }


    /**
     * ファイルの拡張子に合致した拡張子Enumオブジェクトを取得します。<br>
     *
     * @param filename
     * @return 拡張子Enumオブジェクト
     */
    public static EnumExtension getEnumExtension(String filename) {
        String extension = getExtension(filename);

        for (EnumExtension ext : EnumExtension.values()){
            if (ext.getExtension().equalsIgnoreCase(extension)) {
                return ext;
            }
        }
        return null;
    }

    /**
     * HTMLファイルか判定します。<br>
     *
     * @param filename
     * @return HTMLファイル:true
     */
    public static boolean isHtml(String filename) {
        EnumExtension ext = getEnumExtension(filename);

        if (ext == null) {
            return false;
        }

        return ext.isHtml();
    }

    /**
     * 一時ファイル名を取得します。<br>
     * 例:<br>
     * 変換元 -> file:///aaa/bbb/ccc.html
     * 変換後 -> file:///aaa/bbb/ccc_20150310235959999.html
     *
     * @param filename
     * @return 一時ファイル名
     */
    public static String getTemporaryFileName(String filename) {
        String path = removeExtension(filename);
        String extension = getExtension(filename);
        String dateStr = DateUtil.formatDate(new Date(), DateUtil.FORMAT_YYYYMMDDHHMMSSSSS);

        StringBuilder sb = new StringBuilder();
        sb.append(path).append("_").append(dateStr).append(Const.SEPARATOR_EXTENSION).append(extension);

        return sb.toString();
    }

    /**
     * ファイルが存在している場合、削除します。
     *
     * @param file
     */
    public static void deleteQuietly(File file) {
        if (file.exists()) {
            FileUtils.deleteQuietly(file);
        }
    }
}

Sometimes a file is being created but it is empty, sometimes there's no file being created.

I don't what seems to be the problem, because the logcat doesn't include what file it doesn't read. Any kind of help is appreciated.

I see you're getting the path of the file to be written with this line:

 String filePath = getIntent().getStringExtra(SystemInfo.KEY_EDITOR_PREVIEW_URL);

Are you sure the parent directories of the file exist?

In EditorPreviewActivity.java, you can split the full path into two variables the parent directories and the name of the file to be written and then call the method mkdirs() to create the parent directories if they don't exist:

String dirsPath = getIntent().getStringExtra(SystemInfo.KEY_EDITOR_PREVIEW_PATH);
String filePath = dirsPath + getIntent().getStringExtra(SystemInfo.KEY_EDITOR_PREVIEW_FILE_NAME);
boolean directoriesCreated = new File(dirsPath).mkdirs();
LogUtil.d(TAG, "parent directories created?:" + directoriesCreated );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM