قم بإجراء ملف / مجلد مخفي على Windows مع Java
سؤال
أحتاج إلى جعل الملفات والمجلدات المخفية على كل من Windows و Linux. أعلم أن إلحاق "." إلى الجزء الأمامي من ملف أو مجلد سيجعله مخفيا على Linux. كيف أقوم بإجراء ملف أو مجلد مخفي على Windows؟
المحلول
ل Java 6 وتحتم،
ستحتاج إلى استخدام مكالمة أصلية، إليك طريقة واحدة لنظام التشغيل Windows
Runtime.getRuntime().exec("attrib +H myHiddenFile.java");
يجب أن تتعلم قليلا عن Win32-API أو Java الأصلية.
نصائح أخرى
وظيفة التي تريدها هي ميزة NIO.2 في Java 7 القادمة.
إليك مقالة تصف كيفية استخدامها لما تحتاجه: إدارة البيانات الوصفية (ملفات الملف ومتجر الملفات). وبعد هناك مثال مع سمات ملف DOS.:
Path file = ...;
try {
DosFileAttributes attr = Attributes.readDosFileAttributes(file);
System.out.println("isReadOnly is " + attr.isReadOnly());
System.out.println("isHidden is " + attr.isHidden());
System.out.println("isArchive is " + attr.isArchive());
System.out.println("isSystem is " + attr.isSystem());
} catch (IOException x) {
System.err.println("DOS file attributes not supported:" + x);
}
يمكن إجراء سمات الإعداد باستخدام dosfileattrobuteview.
بالنظر إلى هذه الحقائق، أشك في أن هناك طريقة قياسية وأنيقة لإنجاز ذلك في Java 6 أو Java 5.
يمكن ل Java 7 إخفاء ملف DOS بهذه الطريقة:
Path path = ...;
Boolean hidden = path.getAttribute("dos:hidden", LinkOption.NOFOLLOW_LINKS);
if (hidden != null && !hidden) {
path.setAttribute("dos:hidden", Boolean.TRUE, LinkOption.NOFOLLOW_LINKS);
}
في وقت سابق لا يستطيع Java-s.
لا يلقي الرمز أعلاه استثناء على أنظمة الملفات غير DOS. إذا كان اسم الملف يبدأ بفترة، فسيكون أيضا مخفيا على أنظمة ملفات UNIX.
هذا هو ما أستخدمه:
void hide(File src) throws InterruptedException, IOException {
// win32 command line variant
Process p = Runtime.getRuntime().exec("attrib +h " + src.getPath());
p.waitFor(); // p.waitFor() important, so that the file really appears as hidden immediately after function exit.
}
على Windows، باستخدام Java Nio، الملفات
Path path = Paths.get(..); //< input target path
Files.write(path, data_byte, StandardOpenOption.CREATE_NEW); //< if file not exist, create
Files.setAttribute(path, "dos:hidden", Boolean.TRUE, LinkOption.NOFOLLOW_LINKS); //< set hidden attribute
فيما يلي نموذج كود Java 7 القابل للتجميع الذي يخفي ملف تعريفي على Windows.
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.DosFileAttributes;
class A {
public static void main(String[] args) throws Exception
{
//locate the full path to the file e.g. c:\a\b\Log.txt
Path p = Paths.get("c:\\a\\b\\Log.txt");
//link file to DosFileAttributes
DosFileAttributes dos = Files.readAttributes(p, DosFileAttributes.class);
//hide the Log file
Files.setAttribute(p, "dos:hidden", true);
System.out.println(dos.isHidden());
}
}
للتحقق من الملف مخفي. انقر بزر الماوس الأيمن فوق الملف المعني وسترى بعد تنفيذ المحكمة أن الملف المعني مخفي حقا.
String cmd1[] = {"attrib","+h",file/folder path};
Runtime.getRuntime().exec(cmd1);
استخدم هذا الرمز قد يحلك مشكلة