Channel va Bufer yordamida fayl yozish Channel yordamida faylga ma'lumotlarni yozish uchun biz quyidagi amallarni bajarishimiz kerak:
1. Birinchidan, FileOutputStream ob'ektini olishimiz kerak
2. FileOutputStream-dan getChannel() usulini chaqirish orqali FileChannel-ni oling.
3. ByteBuffer yarating va keyin uni ma'lumotlar bilan to'ldiring
4. Keyin ByteBuffer ning flip() usulini chaqirishimiz va uni write() argumenti sifatida topshirishimiz kerak.
FileChannel usuli
5. Yozishni tugatganimizdan so'ng, biz resursni yopishimiz kerak
import java.io.*;
import java.nio.*;
public class FileChannelWrite {
public static void main(String[] args) {
File outputFile = new File("hello.txt");
String text = "I love Bangladesh.";
try {
FileOutputStream fos = new FileOutputStream(outputFile);
FileChannel fileChannel = fos.getChannel();
byte[] bytes = text.getBytes();
ByteBuffer buffer = ByteBuffer.wrap(bytes);
fileChannel.write(buffer);
fileChannel.close();
} catch (java.io.IOException e) {
e.printStackTrace();
}
}
}
PrintStream yordamida fayl yozish Fayl yozish uchun PrintStream sinfidan foydalanishimiz mumkin. Unda har qanday ma'lumotlar turi qiymatlarini chop etish imkonini beruvchi bir necha usullar mavjud.
println() usuli yangi qator qo'shadi. Chop etishni tugatgandan so'ng, biz PrintStreamni tozalashimiz kerak.
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.time.LocalDate;
public class FileWritingDemo {
public static void main(String[] args) {
String destination = "file1.txt";
try(PrintStream ps = new PrintStream(destination)){
ps.println("Stackoverflow documentation seems fun.");
ps.println();
ps.println("I love Java!");
ps.printf("Today is: %1$tm/%1$td/%1$tY", LocalDate.now());
ps.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Katalogda takrorlash va fayl bo'yicha filtrlash
kengaytma