में .txt विस्तार जोड़ मैं एक विधि है कि एक JTextArea से पाठ मिलता है, एक फाइल बना सकते हैं और नीचे दिए गए कोड के रूप में इस पर पाठ लिखने:JFileChooser
public void createTxt() {
TxtFilter txt = new TxtFilter();
JFileChooser fSave = new JFileChooser();
fSave.setFileFilter(txt);
int result = fSave.showSaveDialog(this);
if(result == JFileChooser.APPROVE_OPTION) {
File sFile = fSave.getSelectedFile();
FileFilter selectedFilter = fSave.getFileFilter();
String file_name = sFile.getName();
String file_path = sFile.getParent();
try{
if(!sFile.exists()) {
sFile.createNewFile();
BufferedWriter out = new BufferedWriter(new FileWriter(sFile));
out.write(jTextArea1.getText());
out.close();
JOptionPane.showMessageDialog(null, "Warning file • " + file_name + " • created succesfully in \n" + file_path);
} else {
String message = "File • " + file_name + " • already exist in \n" + file_path + ":\n" + "Do you want to overwrite?";
String title = "Warning";
int reply = JOptionPane.showConfirmDialog(null, message, title, JOptionPane.YES_NO_OPTION);
if(reply == JOptionPane.YES_OPTION){
sFile.delete();
sFile.createNewFile();
BufferedWriter out = new BufferedWriter(new FileWriter(sFile));
out.write(jTextArea1.getText());
out.close();
JOptionPane.showMessageDialog(null, "File • " + file_name + " • overwritten succesfully in \n" + file_path);
}
}
}
catch(IOException e) {
System.out.println("Error");
}
}
}
और एक txt फ़ाइल फिल्टर
public class TxtFilter extends FileFilter{
@Override
public boolean accept(File f){
return f.getName().toLowerCase().endsWith(".txt")||f.isDirectory();
}
@Override
public String getDescription(){
return "Text files (*.txt)";
}
}
txt के लिए फ़ाइल फ़िल्टर ठीक काम करता है लेकिन जब मैं फ़ाइल नाम टाइप करता हूं तो ".txt" एक्सटेंशन जोड़ना चाहता हूं।
मुझे अपने कोड को कैसे संशोधित करना है?
JFileChooser fS = new JFileChooser();
String fileExt = ".txt";
addFileExtIfNecessary(fS.getSelectedFile().getName(),fileExt)
यह काम नहीं करता है .. कोई एक्सटेंशन नहीं जोड़ा –
बहुत अजीब! मेरे सिस्टम पर सबकुछ काम करता है..मैंने जवाब संपादित किया। –
आपके उपयोगी इंफोस के लिए बहुत बहुत धन्यवाद! आप सही हैं मैंने फ़ाइल में दो बार लिखा था, इसके लिए कोई कारण नहीं है। अब फाइलें प्रत्यय के साथ सही ढंग से सहेजी गई हैं ".txt –