-
Một đối tượng có thể
File
tương ứng với một tệp chưa tồn tại không?Có, nếu bạn chuyển giá trị thư mục cho hàm tạo.
String dirPath = "/"; File f = new File(dirPath); File[] files = f.listFiles();
Điều này được thực hiện, ví dụ, để có được một mảng các tập tin.
public class MyClass { public static void main(String[] args) { boolean isObject = false; File file = new File("/"); if (file instanceof Object){ isObject = true; } boolean isFile = file.isFile(); // Tests whether the file denoted by this abstract pathname is a normal file. Это из documentации System.out.println(isObject + " "+ isFile); } }
Đầu ra:
đúng saiFile
kế thừa từobject
. Trả lời có! Tôi đang chờ đợi ý kiến của bạn. -
Làm thế nào để chuyển đổi một đối tượng
File
thành loạiPath
?Phương pháp
toPath();
toPath(); //Returns a java.nio.file.Path object constructed from the this abstract path.
-
Tại sao lớp Files lại cần thiết?
Chúng tôi lấy lớp làm cơ sở
File
, thêm một chút gì đó mới vào nó, đổi tên các phương thức và cuối cùng cũng chia nó thành hai. Vì vậy bây giờ có hai lớp mới -Path
vàFiles
.Path
- trên thực tế, đây là một dạng tương tự mới của lớpFile
vàFiles
- đây là một lớp tiện ích (tương tự vớiArrays
& các lớpCollections
), tất cả các phương thức tĩnh của lớp đã được chuyển sang nóFile
. Điều này “đúng hơn” theo quan điểm của OOP.MMột số từ các tài liệu:
public final class Files
extends Object
Lớp này chỉ bao gồm các phương thức tĩnh hoạt động trên các tệp, thư mục hoặc các loại tệp khác.
Trong hầu hết các trường hợp, các phương thức được xác định ở đây sẽ ủy quyền cho nhà cung cấp hệ thống tệp được liên kết để thực hiện các thao tác với tệp. -
Bạn biết những lớp lưu trữ nào?
Một bài viết hay về chủ đề này và một đoạn trích từ nó: Lưu trữ trong Java
Có hai gói trong đặc tả Java để làm việc với các kho lưu trữ -
java.util.zip
vàjava.util.jar
tương ứng cho các kho lưu trữ zip và jar. Sự khác biệt giữa định dạng jar và zip chỉ nằm ở phần mở rộng của kho lưu trữ zip. Một góijava.util.jar
cũng tương tự như một góijava.util.zip
, ngoại trừ việc triển khai các hàm tạo và một phương thứcvoidputNextEntry(ZipEntry e)
lớpJarOutputStream
. Chỉ có gói sẽ được thảo luận dưới đâyjava.util.jar
. Để chuyển đổi tất cả các ví dụ sang sử dụng kho lưu trữ zip, chỉ cần thay thế Jar bằng Zip ở mọi nơi trong mã. -
Làm cách nào để thêm thư mục vào kho lưu trữ?
Đối với bản thân tôi, tôi hiểu câu hỏi này giống như việc thêm một thư mục trống vào kho lưu trữ đã hoàn thành. Tôi không tìm thấy bất kỳ ví dụ hoạt động nào. Đây là đoạn mã: (Nó cho thấy rõ rằng bạn có thể đặt bất kỳ tệp nào vào kho lưu trữ, nhưng với một thư mục trống... Tôi không biết trả lời thế nào, tôi không đăng lên StackOverFlow, câu hỏi như vậy chắc chắn sẽ là bị đánh giá thấp) Nếu có ai có bất kỳ đề xuất nào, hãy viết.
public class Main { public static void main(String[] args) { String[] myFiles = {"D:\\forJava\\MyArtifactName\\packForTest\\res2.txt", "D:\\forJava\\MyArtifactName\\packForTest\\res.txt", "D:\\forJava\\MyArtifactName\\packForTest\\res4.txt", "D:\\forJava\\MyArtifactName\\packForTest\\testDir\\" }; String zipFile = "D:\\forJava\\MyArtifactName\\packForTest\\res.zip"; ZipUtility zipUtil = new ZipUtility(); try { zipUtil.zip(myFiles, zipFile); } catch (Exception ex) { // some errors occurred ex.printStackTrace(); } } }
Câu hỏi đặt ra là về testDir cuối cùng, JVM không đưa nó vào kho lưu trữ kết quả, với tất cả các tệp txt khác, nó hoạt động tốt.
ZipUtility.java
:import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class ZipUtility { private static final int BUFFER_SIZE = 4096; public void zip(List<File> listFiles, String destZipFile) throws IOException { ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(destZipFile)); for (File file : listFiles) { if (file.isDirectory()) { zipDirectory(file, file.getName(), zos); } else { zipFile(file, zos); } } zos.flush(); zos.close(); } public void zip(String[] files, String destZipFile) throws IOException { List<File> listFiles = new ArrayList<File>(); for (int i = 0; i < files.length; i++) { listFiles.add(new File(files[i])); } zip(listFiles, destZipFile); } private void zipDirectory(File folder, String parentFolder, ZipOutputStream zos) throws IOException { for (File file : folder.listFiles()) { if (file.isDirectory()) { zipDirectory(file, parentFolder + "/" + file.getName(), zos); continue; } zos.putNextEntry(new ZipEntry(parentFolder + "/" + file.getName())); BufferedInputStream bis = new BufferedInputStream( new FileInputStream(file)); long bytesRead = 0; byte[] bytesIn = new byte[BUFFER_SIZE]; int read = 0; while ((read = bis.read(bytesIn)) != -1) { zos.write(bytesIn, 0, read); bytesRead += read; } zos.closeEntry(); } } private void zipFile(File file, ZipOutputStream zos) throws IOException { zos.putNextEntry(new ZipEntry(file.getName())); BufferedInputStream bis = new BufferedInputStream(new FileInputStream( file)); long bytesRead = 0; byte[] bytesIn = new byte[BUFFER_SIZE]; int read = 0; while ((read = bis.read(bytesIn)) != -1) { zos.write(bytesIn, 0, read); bytesRead += read; } zos.closeEntry(); } }
Mã từ đây
-
Tại sao chúng cần thiết
Properties
?Properties
là một tập tin thuộc tính. Cấu trúc của nó: key – value. Để làm việc với những tập tin như vậy, Java có một lớpProperties
, nó được kế thừa từHashTable<Object, Object>
Có một bài viết về thao tác với nó - Ví dụ về tệp Thuộc tính Java
-
Dữ liệu được lưu trữ trong tập tin ở dạng nào
.properties
?Điều quan trọng là ý nghĩa.
-
Có thể thay đổi dữ liệu trong một đối tượng
Properties
sau khi tải nó từ một tệp không?Если он унаследован от
HashMap
, тогда можно, только потом нужно будет изменения в этот файл отписать. Для этого есть методsetProperty
.Вот code:
import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Properties; /** * Created by Роман on 12.09.2016. */ public class LoadAndSetProperties { public static void main(String[] args) { Properties prop = new Properties(); InputStream input = null; try { input = new FileInputStream("D:\\forJava\\MyArtifactName\\packForTest\\config.properties"); // load a properties file prop.load(input); // get the property value and print it out prop.setProperty("database", "ddfdfdfdfdf"); System.out.print(prop.getProperty("database")); } catch (IOException ex) { ex.printStackTrace(); } finally { if (input != null) { try { input.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
Вывод:
ddfdfdfdfdf -
Зачем нужен класс
FileReader
?Java Docs:
public class FileReader
extends InputStreamReader
Convenience class for reading character files. The constructors of this class assume that the default character encoding and the default byte-buffer size are appropriate. To specify these values yourself, construct an InputStreamReader on a FileInputStream.
FileReader is meant for reading streams of characters.
Класс для чтения символов файлов. Конструкторы этого класса предполагают, что codeировка символов дефолтная и дефолтный размер буфера являются подходящими. Whatбы задать эти значения самостоятельно, следует построить
InputStreamReader
надFileInputStream
.FileReader
предназначен для считывания потоков символов. -
Зачем нужен класс
FileWriter
?public class FileWriter
extends OutputStreamWriter
Convenience class for writing character files. The constructors of this class assume that the default character encoding and the default byte-buffer size are acceptable. To specify these values yourself, construct an OutputStreamWriter on a FileOutputStream.
Whether or not a file is available or may be created depends upon the underlying platform. Some platforms, in particular, allow a file to be opened for writing by only one FileWriter (or other file-writing object) at a time. In such situations the constructors in this class will fail if the file involved is already open. FileWriter is meant for writing streams of characters.
Класс для записи символов файлов. Конструкторы этого класса предполагают, что codeировка символов дефолтная и дефолтный размер буфера являются приемлемым. Whatбы задать эти значения самостоятельно, следует построить
OutputStreamWriter
надFileOutputStream
. Является ли файл доступен для записи, зависит от используемой платформы. Некоторые платформы разрешают держать файл для записи только однимFileWriter
(or другого an object записи file), в одно время.FileWriter
предназначен для записи потоков символов. Для написания потоков необработанных byteов, используйтеFileOutputStream
.Эти классы (
FileReader
иFileWriter
) специально ориентированы для работы с текстом и строками.
DefNeo
Mức độ
GO TO FULL VERSION