Uyenza njani ifayile yexeshana kwiJava

Kukho amaxesha apho kufuneka senze iifayile zexeshana kubhabho ukugcina ulwazi kunye nokuzicima emva koko.

KwiJava, sinokusebenzisa Files.createTempFile() iindlela zokwenza iifayile zethutyana.



Yenza Iifayile Zethutyana

Lo mzekelo ulandelayo usebenzisa Files.createTempFile(prefix, suffix) ukwenza ifayile yexeshana.


import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; public class CreateTempFile {
public static void main(String[] args) {

try {

// Create a temporary file

Path tempFile = Files.createTempFile('temp-', '.txt');

System.out.println('Temp file : ' + temp);

} catch (IOException e) {

e.printStackTrace();
}
} }

Iziphumo:

Temp file : /var/folders/nyckvw0000gr/T/temp-2129139085984899264.txt

Apha, 'temp-' isimaphambili kunye '.text' sisimamva.


Phawula:Ngokuzenzekelayo iJava yenza ifayile yexeshana kulawulo lwethutyana. Singasifumana isikhombisi sethutyana ngokwenza System.getProperty('java.io.tmpdir')

Ukuba isimamva asisebenzi, ifayile yethutyana yenziwe nge .tmp ulwandiso.

Umzekelo:

Path tempFile = Files.createTempFile('prefix-', null); System.out.println('Temp file : ' + tempFile); // Temp file : /var/folders/nyckvw0000gr/T/prefix-17184288103181464441.tmp

Kananjalo ukuba isimamva asibonelelwanga ngefayile ye-temp yenziwe ngaphandle kolwandiso:

Path tempFile = Files.createTempFile(null, ''); System.out.println('Temp file : ' + tempFile); // Temp file : /var/folders/nyckvw0000gr/T/1874152090427250275

Yenza Ifayile yeTempsi kulawulo oluchaziweyo

Endaweni yokuvumela iJava ukuba ikhethe isikhombisi, singasixelela ukuba senze ifayile yexeshana phi.


Umzekelo:

import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class CreateTempFile {
public static void main(String[] args) {

try {

Path path = Paths.get('target/tmp/');

// Create a temporary file in the specified directory.

Path tempFile = Files.createTempFile(path, null, '.log');

System.out.println('Temp file : ' + temp);

} catch (IOException e) {

e.printStackTrace();
}
} }
Phawula:Isikhokelo esichaziweyo kufuneka sibekhona kwifayile yexeshana ukuba ibhalelwe.

Yenza iFayile yeTempsi kwaye ubhale kuyo

Umzekelo olandelayo wekhowudi wenza ifayile yethutyana emva koko ubhale umbhalo othile kuyo:

import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class CreateTempFile {
public static void main(String[] args) {

try {

Path path = Paths.get('target/tmp/');

// Create an temporary file in a specified directory.

Path tempFile = Files.createTempFile(path, null, '.log');

System.out.println('Temp file : ' + tempFile);

// write a line

Files.write(tempFile, 'Hello From Temp File '.getBytes(StandardCharsets.UTF_8));

} catch (IOException e) {

e.printStackTrace();
}
} }

Ukuqhubeka kokufunda: