-
Apa obyek bisa
File
cocog karo file sing durung ana?Ya, yen sampeyan ngirim nilai direktori menyang konstruktor.
String dirPath = "/"; File f = new File(dirPath); File[] files = f.listFiles();
Iki rampung, contone, kanggo njupuk Uploaded 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:
bener palsuFile
warisan sakaobject
. Wangsulan: ya! Aku ngenteni komentar sampeyan. -
Kepiye carane ngowahi obyek
File
dadi jinisPath
?Metode
toPath();
toPath(); //Returns a java.nio.file.Path object constructed from the this abstract path.
-
Napa kelas Files dibutuhake?
We njupuk kelas minangka basis
File
, nambah sethitik soko anyar kanggo iku, ngganti jeneng cara, lan ing pungkasan uga dibagi dadi loro. Dadi saiki ana rong kelas anyar -Path
lanFiles
.Path
- iki, nyatane, analog anyar saka kelasFile
, lanFiles
- iki minangka kelas sarana (kanthi analogi karoArrays
& kelasCollections
), kabeh cara statis saka kelas wis ditransfer menyangFile
. Iki "luwih bener" saka sudut pandang OOP.MSawetara saka dokumen:
public final class Files
extends Object
Kelas iki mung kalebu metode statis sing beroperasi ing file, direktori, utawa jinis file liyane.
Umume kasus, cara sing ditetepake ing kene bakal utusan menyang panyedhiya sistem file sing gegandhengan kanggo nindakake operasi file. -
Apa kelas pengarsipan sing sampeyan ngerti?
Artikel sing apik babagan topik iki lan kutipan saka iku: Arsip ing Jawa
Ana rong paket ing spesifikasi Jawa kanggo nggarap arsip -
java.util.zip
lanjava.util.jar
masing-masing kanggo arsip zip lan jar. Bentenipun antarane format jar lan zip mung ing extension saka arsip zip. Paketjava.util.jar
padha karo paketjava.util.zip
, kajaba implementasine konstruktor lan metodevoidputNextEntry(ZipEntry e)
kelasJarOutputStream
. Mung paket kasebut bakal dibahas ing ngisor ikijava.util.jar
. Kanggo ngowahi kabeh conto kanggo nggunakake arsip zip, mung ngganti Jar karo Zip nang endi wae ing kode. -
Kepiye cara nambah direktori menyang arsip?
Kanggo aku, aku ngerti pitakonan iki minangka nambah direktori kosong menyang arsip sing wis rampung. Aku ora nemokake conto sing bisa digunakake. Punika kode: (Iku cetha nuduhake yen sampeyan bisa sijine file sembarang ing arsip, nanging karo direktori kosong ... Aku ora ngerti carane njawab, Aku ora ngirim ing StackOverFlow, pitakonan kuwi mesthi bakal. downvoted) Yen ana sing duwe saran, tulisen.
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(); } } }
Pitakonan iku bab testDir pungkasan, JVM ora sijine ing arsip asil, karo kabeh file txt liyane bisa metu nggoleki.
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(); } }
Kode saka kene
-
Yagene padha dibutuhake
Properties
?Properties
yaiku file properti. Struktur: kunci - nilai. Kanggo nggarap file kasebut, Java duwe kelasProperties
, sing diwarisakeHashTable<Object, Object>
Ana artikel babagan manipulasi - conto file Java Properties
-
Ing wangun apa data sing disimpen ing file
.properties
?Kuncine yaiku makna.
-
Apa bisa ngganti data ing obyek
Properties
sawise dimuat saka file?Yen diwarisake saka
HashMap
, sampeyan bisa, mung sampeyan kudu mbatalake owah-owahan ing file iki. Ana cara kanggo ikisetProperty
.Iki kode:
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
tingkat
GO TO FULL VERSION