Java ဖန်တီးပြီး ဖိုင်များသို့ ရေးပါ။
ဖိုင်တစ်ခုဖန်တီးပါ။
Java တွင် ဖိုင်တစ်ခုဖန်တီးရန်၊ သင်သည် createNewFile()
နည်းလမ်းကို အသုံးပြုနိုင်သည်။ ဤနည်းလမ်းသည် ဘူလီယံတန်ဖိုးကို ပြန်ပေးသည်- true
အကယ်၍ ဖိုင်ကို အောင်မြင်စွာ ဖန်တီးခဲ့ false
လျှင် နှင့် ဖိုင်ရှိပြီးသားဖြစ်လျှင်၊ နည်းလမ်းကို try...catch
ဘလောက်တစ်ခုတွင် ထည့်သွင်းထားကြောင်း သတိပြုပါ။ IOException
error ဖြစ်ပေါ်ပါက (ဖိုင်ကို အကြောင်းတစ်ခုခုကြောင့် ဖန်တီး၍မရပါက) လွှတ် တင်သောကြောင့် ၎င်းသည် လိုအပ်ပါသည် ။
ဥပမာ
import java.io.File; // Import the File class
import java.io.IOException; // Import the IOException class to handle errors
public class CreateFile {
public static void main(String[] args) {
try {
File myObj = new File("filename.txt");
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
အထွက်သည်-
File created: filename.txt
သီးခြားလမ်းညွှန်တစ်ခုတွင် ဖိုင်တစ်ခုဖန်တီးရန် (ခွင့်ပြုချက်လိုအပ်သည်)၊ ဖိုင်၏လမ်းကြောင်းကို သတ်မှတ်ပြီး " \
" စာလုံး ( Windows အတွက် ) မှလွတ်မြောက်ရန် double backslashes ကိုအသုံးပြုပါ။ Mac နှင့် Linux တွင် သင်သည် - /Users/name/filename.txt ကဲ့သို့သော လမ်းကြောင်းကို ရေးနိုင်သည်။
ဥပမာ
File myObj = new File("C:\\Users\\MyName\\filename.txt");
ဖိုင်တစ်ခုသို့ ရေးပါ။
အောက်ပါဥပမာတွင်၊ အထက်နမူနာတွင် ကျွန်ုပ်တို့ဖန်တီးထားသောဖိုင်သို့ စာသားအချို့ရေးရန် FileWriter
၎င်း၏နည်းလမ်းဖြင့် အတန်း ကို အသုံးပြုသည်။ write()
ဖိုင်ကို စာရေးပြီးသောအခါ၊ ၎င်းကို close()
နည်းလမ်းဖြင့် ပိတ်သင့်သည်-
ဥပမာ
import java.io.FileWriter; // Import the FileWriter class
import java.io.IOException; // Import the IOException class to handle errors
public class WriteToFile {
public static void main(String[] args) {
try {
FileWriter myWriter = new FileWriter("filename.txt");
myWriter.write("Files in Java might be tricky, but it is fun enough!");
myWriter.close();
System.out.println("Successfully wrote to the file.");
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
အထွက်သည်-
Successfully wrote to the file.
အထက်ပါဖိုင်ကို ဖတ်ရန် Java Read Files အခန်းသို့သွားပါ။