-
Maaari bang tumutugma ang isang bagay
File
sa isang file na hindi pa umiiral?Oo, kung ipapasa mo ang halaga ng direktoryo sa tagabuo.
String dirPath = "/"; File f = new File(dirPath); File[] files = f.listFiles();
Ginagawa ito, halimbawa, upang makakuha ng isang hanay ng mga file.
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); } }
Output:
true falseFile
namamana mula saobject
. Sagot: oo! Naghihintay ako sa iyong mga komento. -
Paano i-convert ang isang bagay
File
upang mag-typePath
?Pamamaraan
toPath();
toPath(); //Returns a java.nio.file.Path object constructed from the this abstract path.
-
Bakit kailangan ang klase ng Files?
Kinuha namin ang klase bilang batayan
File
, nagdagdag ng kaunting bago dito, pinalitan ang pangalan ng mga pamamaraan, at sa dulo ay hinati din ito sa dalawa. Kaya ngayon ay may dalawang bagong klase -Path
atFiles
.Path
- ito ay, sa katunayan, isang bagong analogue ng classFile
, atFiles
- ito ay isang utility class (sa pamamagitan ng pagkakatulad saArrays
& classesCollections
), lahat ng mga static na pamamaraan ng klase ay inilipat ditoFile
. Ito ay "mas tama" mula sa punto ng view ng OOP.MAng ilan mula sa mga dokumento:
public final class Files
extends Object
Ang klase na ito ay eksklusibong binubuo ng mga static na pamamaraan na gumagana sa mga file, direktoryo, o iba pang uri ng mga file.
Sa karamihan ng mga kaso, ang mga pamamaraan na tinukoy dito ay magdedelegate sa nauugnay na file system provider upang isagawa ang mga pagpapatakbo ng file. -
Anong mga klase sa pag-archive ang alam mo?
Isang magandang artikulo sa paksang ito at isang sipi mula dito: Pag-archive sa Java
Mayroong dalawang pakete sa pagtutukoy ng Java para sa pagtatrabaho sa mga archive -
java.util.zip
atjava.util.jar
ayon sa pagkakabanggit para sa mga archive ng zip at jar. Ang pagkakaiba sa pagitan ng mga format ng jar at zip ay nasa extension lamang ng zip archive. Ang isang paketejava.util.jar
ay katulad ng isang paketejava.util.zip
, maliban sa pagpapatupad ng mga konstruktor at isang paraan ngvoidputNextEntry(ZipEntry e)
klaseJarOutputStream
. Ang pakete lamang ang tatalakayin sa ibabajava.util.jar
. Para i-convert ang lahat ng halimbawa para gumamit ng zip archive, palitan lang ang Jar ng Zip sa lahat ng lugar sa code. -
Paano magdagdag ng isang direktoryo sa isang archive?
Para sa aking sarili, naunawaan ko ang tanong na ito bilang pagdaragdag ng isang walang laman na direktoryo sa isang tapos na archive. Wala akong nakitang mga gumaganang halimbawa. Narito ang code: (Malinaw na ipinapakita nito na maaari kang maglagay ng anumang file sa archive, ngunit sa isang walang laman na direktoryo ... Hindi ko alam kung paano sasagot, hindi ako nag-post sa StackOverFlow, ang ganoong tanong ay tiyak na downvoted) Kung mayroong anumang mga mungkahi, sumulat.
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(); } } }
Ang tanong ay tungkol sa huling testDir, hindi ito inilalagay ng JVM sa nagreresultang archive, kasama ang lahat ng iba pang mga txt file na ito ay gumagana nang maayos.
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(); } }
Code mula dito
-
Bakit kailangan sila
Properties
?Properties
ay isang properties file. Ang istraktura nito: susi - halaga. Upang gumana sa mga naturang file, ang Java ay may isang klaseProperties
, ito ay minana mula saHashTable<Object, Object>
Mayroong isang artikulo tungkol sa pagmamanipula nito - mga halimbawa ng file ng Java Properties
-
Sa anong anyo nakaimbak ang data sa file
.properties
?Ang susi ay ang kahulugan.
-
Posible bang baguhin ang data sa isang bagay
Properties
pagkatapos i-load ito mula sa isang file?Kung ito ay minana mula sa
HashMap
, magagawa mo ito, pagkatapos ay kakailanganin mong alisin sa pagkakasulat ang mga pagbabago sa file na ito. May paraan para ditosetProperty
.Narito ang 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(); } } } } }
Output:
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
Antas
GO TO FULL VERSION