سؤال

أريد أن أكون قادرا على تحديث خط معين في ملف نصي.ولكن تظهر لي رسالة خطأ أنه لا يمكن حذف الملف, لماذا لا يمكنني الحصول على هذا الخطأ ؟

public class Main {
    public static void main(String[] args) {
        Main rlf = new Main();
        rlf.removeLineFromFile("F:\\text.txt", "bbb");
    }

    public void removeLineFromFile(String file, String lineToRemove) {
        try {
            File inFile = new File(file);

            if (!inFile.isFile()) {
                System.out.println("Parameter is not an existing file");
                return;
            }

            //Construct the new file that will later be renamed to the original filename.
            File tempFile = new File(inFile.getAbsolutePath() + ".tmp");

            BufferedReader br = new BufferedReader(new FileReader(file));
            PrintWriter pw = new PrintWriter(new FileWriter(tempFile));

            String line = null;

            //Read from the original file and write to the new
            //unless content matches data to be removed.
            while ((line = br.readLine()) != null) {

                if (!line.trim().equals(lineToRemove)) {

                    pw.println(line);
                    pw.flush();
                }
            }
            pw.close();
            br.close();

            //Delete the original file
            if (!inFile.delete()) {
                System.out.println("Could not delete file");
                return;
            }

            //Rename the new file to the filename the original file had.
            if (!tempFile.renameTo(inFile)) System.out.println("Could not rename file");

        }
        catch (FileNotFoundException ex) {
            ex.printStackTrace();
        }
        catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}​
هل كانت مفيدة؟

المحلول

البرنامج يعمل بالنسبة لي.ربما كنت تواجه مسألة بيئية.

نصائح أخرى

يجب أن ننظر إلى RandomAccessFile.

هذا سوف تتيح لك أن تسعى إلى المكان في ملف تريد التحديث فقط الجزء الذي تريد تحديثه.

كما جاستن أشير أعلاه, يجب أن تكون باستخدام وrandomaccessfile نوع من api إذا كنت ترغب في تعديل أجزاء من الملف.النهج الذي تحاول استخدامه لديها الكثير من المشاكل المحتملة.

  • فإنه يتطلب الملف tmp إلى إنشاء بالإضافة إلى ذلك.قد لا مقياس الملفات الكبيرة (أنا لست على بينة من المشكلة المجال ، على الرغم من)
  • تحاول أن توفق الملفات أيضا يمكن أن يسبب عدة استثناءات ، و تتطلب الكثير من معالجة الخطأ.

يمكنك إنشاء مثيل جديد (ليغلق القديم) من قبل new ثم حذف استخدامه.
نفس الملف حذف مشكلة هنا

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top