Opening a file without the extension - Java - java

Im doing a project for my college, my save/opening file are working all right, but I need them to save as my desired extension, and open like that as well.
For example: When I click on Save File, I write the name testFile as file name and hit save, now the my code must save as my desired extension. Same works for opening file, if I write testFile and hit open, it must locate the testFile.txt. Anyone can give me a hand how I should do this? follow my code below.
private class SalvaDesenho implements ActionListener {
private Component parent;
SalvaDesenho(Component parent) {
this.parent = parent;
}
public void actionPerformed(ActionEvent e) {
try {
final JFileChooser fc = new JFileChooser();
fc.setFileFilter(new FileNameExtensionFilter("Arquivo de Texto (.txt)", "txt"));
fc.setAcceptAllFileFilterUsed(false);
int returnVal = fc.showSaveDialog(parent);
if (returnVal != JFileChooser.APPROVE_OPTION)
return;
int op = 0;
if (fc.getSelectedFile().exists()) {
Object[] options = { "Sim", "Não" };
op = JOptionPane.showOptionDialog(null, "O arquivo já existe deseja substituilo?", "Warning",
JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,
null, options, options[1]);
}
if (op != 0) return;
System.out.println("Salvando: " + fc.getSelectedFile().getPath());
FileOutputStream fout = new FileOutputStream(fc.getSelectedFile());
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(figuras);
isSaved = true;
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
private class AbreDesenho implements ActionListener {
private Component parent;
AbreDesenho(Component parent) {
this.parent = parent;
}
public void actionPerformed(ActionEvent e) {
try {
final JFileChooser fc = new JFileChooser();
FileNameExtensionFilter txtFilter = new FileNameExtensionFilter("Arquivo de texto (.txt)", "txt");
fc.setFileFilter(txtFilter);
int returnVal = fc.showOpenDialog(parent);
if (returnVal != JFileChooser.APPROVE_OPTION)
System.out.println("File error!");
System.out.println("Abrindo: " + fc.getSelectedFile().getPath());
FileInputStream fin = new FileInputStream(fc.getSelectedFile());
ObjectInputStream ois = new ObjectInputStream(fin);
figuras = (Vector<Figura>) ois.readObject();
} catch (Exception ex) {
ex.printStackTrace();
return;
}
pnlDesenho.getGraphics().clearRect(0 , 0, parent.getHeight(), parent.getWidth());
for (int i=0 ; i<figuras.size(); i++)
figuras.get(i).torneSeVisivel(pnlDesenho.getGraphics());
}
}
Thanks.

You have to do this manually:
Get the File object from the JFileChooser
Get its absolute path as a String, using getAbsolutePath().
Check whether it has an extension or not: Check file extension in Java
If not, add your extension to the path: path = path+".txt";
Create a new File object from the path: File file = new File(path)
Open/Save the file (your code)

Related

Saving images using dialogs in java FXML (java 8)

So im trying to save a image (Image class from javafx.scene.image.Image) onto a file with a save file dialog (JFileChooser) so that it is user friendly.
What i want it to do: Save the image specified
What it does: Save dialog works (i think), and it doesn't save (write to file) anything.
Here is the code behind it:
public void saveFile() { //menu item interface for save and save as
JFrame parentFrame = new JFrame();
JFileChooser fileChooser = new JFileChooser();
fileChooser.setDialogTitle("Save");
fileChooser.setCurrentDirectory(new File(System.getProperty("user.home")));
//Setting the file extentions
/*fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("PNG Image", ".png"));
fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("JPG Image", ".jpg"));
fileChooser.addChoosableFileFilter(new FileNameExtensionFilter("BMP Image", ".bmp"));*/
int userSelection = fileChooser.showSaveDialog(parentFrame);
if (userSelection == JFileChooser.APPROVE_OPTION) {
File fileToSave = fileChooser.getSelectedFile(); //selected file
saveToFile(picFrame.getImage(), fileToSave); //save the file
System.out.println("Save as file: " + fileToSave.getAbsolutePath()); //debug because it doesnt work
}
parentFrame.dispose();
}
and here is saveToFile
public static void saveToFile(Image image, File file) {
String extension = "";
File outputFile = file;
try {
if (file != null && file.exists()) {
String name = file.getName();
extension = name.substring(name.lastIndexOf("."));
}
} catch (Exception e) {
extension = "";
}
BufferedImage bImage = SwingFXUtils.fromFXImage(image, null);
try {
ImageIO.write(bImage, extension, outputFile);
System.out.println("Saveing file");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
After some digging arround and debuging i found the problem and the solution , so here it is.
All the code.
public void saveFile() { //menu item interface for save and save as
Window mainStage = ap.getScene().getWindow(); //get ze window
FileChooser fileChooser = new FileChooser(); //Filechooser the class that has the file chooser
fileChooser.setTitle("Open Resource File"); //Title of prompt
fileChooser.getExtensionFilters().addAll( //add filter
new ExtensionFilter("Image Files", "*.png", "*.jpg", "*.gif", ".bmp"), //Filters
new ExtensionFilter("All Files", "*.*")); //Filters
File selectedFile = fileChooser.showSaveDialog(mainStage); //get the file
if (selectedFile != null) { //if something is selected then
System.out.println(selectedFile.getAbsoluteFile()); //debug
System.out.println(selectedFile.getAbsoluteFile().getParent()); //debug
Image img = SwingFXUtils.toFXImage(bImg, null); //convert to Image
saveToFile(img, selectedFile); //save the Image
}
}
/**
* A simple image save
*
* #param image The image you want to save
* #param file The file where you want to save it
*/
public static void saveToFile(Image image, File file) {
File outputFile = file; //file
BufferedImage bImage = SwingFXUtils.fromFXImage(image, null); //Convert to bufferedimage
try {
ImageIO.write(bImage, getFileExtension(outputFile).toUpperCase(), outputFile.getAbsoluteFile()); //actualy save
System.out.println("Saveing file ex: " + getFileExtension(outputFile).toUpperCase() + " to: " + outputFile.getAbsoluteFile() + " with name " + outputFile.getName());
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private static String getFileExtension(File file) {
String name = file.getName();
int lastIndexOf = name.lastIndexOf(".") + 1;
if (lastIndexOf == -1) {
return ""; // empty extension
}
return name.substring(lastIndexOf);
}

error: no suitable constructor found for FileDialog(Notepad,String,int)

import java.awt.*;
import java.awt.event.*;
import java.io.*;
class Notepad implements ActionListener {
Frame f;
MenuBar mb;
Menu m1, m2;
MenuItem nw, opn, sve, sveas, ext, fnd, fr;
TextArea t;
// [...Constructor removed...]
public void actionPerformed(ActionEvent e) {
if (e.getSource() == nw) {
t.setText(" ");
} else if (e.getSource() == opn) {
try {
FileDialog fd = new FileDialog(this, "Open File", FileDialog.LOAD); // <- Does not compile
fd.setVisible(true);
String dir = fd.getDirectory();
String fname = fd.getFile();
FileInputStream fis = new FileInputStream(dir + fname);
DataInputStream dis = new DataInputStream(fis);
String str = " ", msg = " ";
while ((str = dis.readLine()) != null) {
msg = msg + str;
msg += "\n";
}
t.setText(msg);
dis.close();
} catch (Exception ex) {
System.out.print(ex.getMessage());
}
}
}
// [...]
}
I get:
error: no suitable constructor found for FileDialog(Notepad,String,int)
FileDialog fd=new FileDialog(this,"Open File",FileDialog.LOAD);
FileDialog fd=new FileDialog(this,"Open File",FileDialog.LOAD); wrong.
This first param must be a Frame which is the parent. maybe use:
FileDialog fd=new FileDialog(f,"Open File",FileDialog.LOAD);
Plz look at this: https://docs.oracle.com/javase/7/docs/api/java/awt/FileDialog.html
FileDialog fd=new FileDialog(this,"Open File",FileDialog.LOAD);
You're using this as the first parameter, and this refers to the instance of the class you are currently working on, so to a Notepad. For example if you use, somewhere else in your code:
Notepad np = new Notepad();
//...
np.actionPerformed(ae); //ae is an ActionEvent
Then this refers to np. You should use
FileDialog fd=new FileDialog(f,"Open File",FileDialog.LOAD);
EDIT: Another user preceded me with a very similar answer, sorry

Image didn't load in JPanel

I have a JPanel name "imagePanel" and a button name "browseBtn". All contained in a JFrame class. When pressing the browseBtn, a file chooser will open up and after choosing a PNG image file, the image will appear directly in the imagePanel.
This is the action event for the browseBtn
private void browseBtnActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
JFileChooser fc = new JFileChooser();
int result = fc.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
if (accept(file)) {
try {
ImageIcon image = new ImageIcon(file.getPath());
JLabel l = new JLabel(image);
imagePanel.add(l);
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Error reading file !");
}
}
else {
JOptionPane.showMessageDialog(this, "Choose png file only !");
}
}
}
public boolean accept(File file) {
return file.isDirectory() || file.getAbsolutePath().endsWith(".png");
}
I have choose the correct .png file but i don't understand why the image didn't show up in the imagePanel. Can you guy explain on that ?
Cheers.
You should avoid creating new objects everytime you want to display your image, imagine if you change it 5 times, you're creating 5 times an object while you display only one !
Like said in the comments, your best shot would be to create your label when you create your panel, add it to said panel, then simply change the icon of this label when you load your image.
browseBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser fc = new JFileChooser();
int result = fc.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
if (accept(file)) {
try {
ImageIcon image = new ImageIcon(file.getPath());
label.setIcon(image);
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, "Error reading file !");
}
}
else {
JOptionPane.showMessageDialog(this, "Choose png file only !");
}
}
}
public boolean accept(File file) {
return file.isDirectory() || file.getAbsolutePath().endsWith(".png");
}
});
Assuming label is the reference to said JLabel, created on components initialisation.
Or you might try this :
browseBtn.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JFileChooser fc = new JFileChooser();
int result = fc.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
if (accept(file)) {
try {
ImageIcon imageIcon = new ImageIcon(new ImageIcon(file.getPath()).getImage().getScaledInstance(20, 20, Image.SCALE_DEFAULT)); //resizing
label.setIcon(imageIcon);
/*try { // or try this
InputStream inStream = this.getClass().getClassLoader().getResourceAsStream(file.getPath());
BufferedImage img = ImageIO.read(inStream);
Image rimg = img.getScaledInstance(width, height, Image.SCALE_STANDARD);
label.setIcon(rimg);
} catch (IOException e) {}*/
} catch (Exception ex) {JOptionPane.showMessageDialog(this, "Error reading file !");}
} else {JOptionPane.showMessageDialog(this, "Choose png file only !");}
}
}
public boolean accept(File file) {
return file.isDirectory() || file.getAbsolutePath().endsWith(".png");
}
});

How to save desktop application state?

I am creating an editor in java. I would like to know how to save an intermediate state in java?
For Example when user wants to save the changes done on the editor, how could it be done and also should be reloaded later.
Eg. powerpoint application is saved as .ppt or .pptx. Later the same .ppt while could be opened for further editions. I hope I am clear with my requirement.
The Preferences API with user preferences; most recently edited files, per file maybe timestamp + cursor position, GUI settings.
To save the contents of JTextPane you can serialize the DefaultStyledDocument of JTextPane in a file using proper way of serialization. And when you want to load the content again you can deserialize the same and display it on the JTextPane . Consider the code given below:
import javax.swing.*;
import javax.swing.text.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
public class SaveEditor extends JFrame implements ActionListener{
public static final String text = "As told by Wikipedia\n"
+"Java is a general-purpose, concurrent, class-based, object-oriented computer programming language."
+ "It is specifically designed to have as few implementation "
+ "dependencies as possible. It is intended to let application developers write once, run anywhere (WORA), "
+ "meaning that code that runs on one platform does not need to be recompiled to run on another. "
+ "Java applications are typically compiled to bytecode (class file) that can run on any Java virtual "
+ "machine (JVM) regardless of computer architecture. Java is, as of 2012, one of the most popular programming "
+ "languages in use, particularly for client-server web applications, with a reported 10 million users.";
JTextPane pane ;
DefaultStyledDocument doc ;
StyleContext sc;
JButton save;
JButton load;
public static void main(String[] args)
{
try
{
UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
SaveEditor se = new SaveEditor();
se.createAndShowGUI();
}
});
} catch (Exception evt) {}
}
public void createAndShowGUI()
{
setTitle("TextPane");
sc = new StyleContext();
doc = new DefaultStyledDocument(sc);
pane = new JTextPane(doc);
save = new JButton("Save");
load = new JButton("Load");
JPanel panel = new JPanel();
panel.add(save);panel.add(load);
save.addActionListener(this);load.addActionListener(this);
final Style heading2Style = sc.addStyle("Heading2", null);
heading2Style.addAttribute(StyleConstants.Foreground, Color.red);
heading2Style.addAttribute(StyleConstants.FontSize, new Integer(16));
heading2Style.addAttribute(StyleConstants.FontFamily, "serif");
heading2Style.addAttribute(StyleConstants.Bold, new Boolean(true));
try
{
doc.insertString(0, text, null);
doc.setParagraphAttributes(0, 1, heading2Style, false);
} catch (Exception e)
{
System.out.println("Exception when constructing document: " + e);
System.exit(1);
}
getContentPane().add(new JScrollPane(pane));
getContentPane().add(panel,BorderLayout.SOUTH);
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public void actionPerformed(ActionEvent evt)
{
if (evt.getSource() == save)
{
save();
}
else if (evt.getSource() == load)
{
load();
}
}
private void save()//Saving the contents .
{
JFileChooser chooser = new JFileChooser(".");
chooser.setDialogTitle("Save");
int returnVal = chooser.showSaveDialog(this);
if(returnVal == JFileChooser.APPROVE_OPTION)
{
File file = chooser.getSelectedFile();
if (file != null)
{
FileOutputStream fos = null;
ObjectOutputStream os = null;
try
{
fos = new FileOutputStream(file);
os = new ObjectOutputStream(fos);
os.writeObject(doc);
JOptionPane.showMessageDialog(this,"Saved successfully!!","Success",JOptionPane.INFORMATION_MESSAGE);
}
catch (Exception ex)
{
ex.printStackTrace();
}
finally
{
if (fos != null)
{
try
{
fos.close();
}
catch (Exception ex){}
}
if (os != null)
{
try
{
os.close();
}
catch (Exception ex){}
}
}
}
else
{
JOptionPane.showMessageDialog(this,"Please enter a fileName","Error",JOptionPane.ERROR_MESSAGE);
}
}
}
private void load()//Loading the contents
{
JFileChooser chooser = new JFileChooser(".");
chooser.setDialogTitle("Open");
chooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
int returnVal = chooser.showOpenDialog(this);
if(returnVal == JFileChooser.APPROVE_OPTION)
{
File file = chooser.getSelectedFile();
if (file!= null)
{
FileInputStream fin = null;
ObjectInputStream ins = null;
try
{
fin = new FileInputStream(file);
ins = new ObjectInputStream(fin);
doc = (DefaultStyledDocument)ins.readObject();
pane.setStyledDocument(doc);
JOptionPane.showMessageDialog(this,"Loaded successfully!!","Success",JOptionPane.INFORMATION_MESSAGE);
}
catch (Exception ex)
{
ex.printStackTrace();
}
finally
{
if (fin != null)
{
try
{
fin.close();
}
catch (Exception ex){}
}
if (ins != null)
{
try
{
ins.close();
}
catch (Exception ex){}
}
}
}
else
{
JOptionPane.showMessageDialog(this,"Please enter a fileName","Error",JOptionPane.ERROR_MESSAGE);
}
}
}
}

Java JTextPane RTF Save

i have the following code trying to save the contents of a JTextPane as RTF. although a file is created in the following code but it is empty!
any tips regarding what am i doing wrong? (as usual dont forget im a beginner!)
if (option == JFileChooser.APPROVE_OPTION) {
////////////////////////////////////////////////////////////////////////
//System.out.println(chooser.getSelectedFile().getName());
//System.out.println(chooser.getSelectedFile().getAbsoluteFile());
///////////////////////////////////////////////////////////////////////////
StyledDocument doc = (StyledDocument)textPaneHistory.getDocument();
RTFEditorKit kit = new RTFEditorKit();
BufferedOutputStream out;
try {
out = new BufferedOutputStream(new FileOutputStream(chooser.getSelectedFile().getName()));
kit.write(out, doc, doc.getStartPosition().getOffset(), doc.getLength());
} catch (FileNotFoundException e) {
} catch (IOException e){
} catch (BadLocationException e){
}
}
EDIT: HTMLEditorKit if i use HTMLEditorKit it works and thats what i really wanted. SOLVED!
if (textPaneHistory.getText().length() > 0){
JFileChooser chooser = new JFileChooser();
chooser.setMultiSelectionEnabled(false);
int option = chooser.showSaveDialog(ChatGUI.this);
if (option == JFileChooser.APPROVE_OPTION) {
StyledDocument doc = (StyledDocument)textPaneHistory.getDocument();
HTMLEditorKit kit = new HTMLEditorKit();
BufferedOutputStream out;
try {
out = new BufferedOutputStream(new FileOutputStream(chooser.getSelectedFile().getAbsoluteFile()));
kit.write(out, doc, doc.getStartPosition().getOffset(), doc.getLength());
} catch (FileNotFoundException e) {
} catch (IOException e){
} catch (BadLocationException e){
}
}
}
here is the solution. it works if HTMLEditorKit is used.
Here is a solution for RTF and not HTML.
As RTF is not standardized, I needed some additional tags like \sb and \sa to force my Wordpad to display the file properly.
protected void exportToRtf() throws IOException, BadLocationException {
final StringWriter out = new StringWriter();
Document doc = textPane.getDocument();
RTFEditorKit kit = new RTFEditorKit();
kit.write(out, doc, doc.getStartPosition().getOffset(), doc.getLength());
out.close();
String rtfContent = out.toString();
{
// replace "Monospaced" by a well-known monospace font
rtfContent = rtfContent.replaceAll("Monospaced", "Courier New");
final StringBuffer rtfContentBuffer = new StringBuffer(rtfContent);
final int endProlog = rtfContentBuffer.indexOf("\n\n");
// set a good Line Space and no Space Before or Space After each paragraph
rtfContentBuffer.insert(endProlog, "\n\\sl240");
rtfContentBuffer.insert(endProlog, "\n\\sb0\\sa0");
rtfContent = rtfContentBuffer.toString();
}
final File file = new File("c:\\temp\\test.rtf");
final FileOutputStream fos = new FileOutputStream(file);
fos.write(rtfContent.toString().getBytes());
fos.close();
}
This is how I did when I faced the same problem.
public void actionPerformed(ActionEvent e) {
text = textPane.getText();
JFileChooser saveFile = new JFileChooser();
int option = saveFile.showSaveDialog(null);
saveFile.setDialogTitle("Save the file...");
if (option == JFileChooser.APPROVE_OPTION) {
File file = saveFile.getSelectedFile();
if (!file.exists()) {
try {
BufferedWriter writer = new BufferedWriter(
new FileWriter(file.getAbsolutePath() + ".rtf"));
writer.write(text);
writer.close();
} catch (IOException ex) {
ex.printStackTrace();
System.out.println(ex.getMessage());
JOptionPane.showMessageDialog(null,
"Failed to save the file");
}
}
else if (file.exists()) {
int confirm = JOptionPane.showConfirmDialog(null,
"File exists do you want to save anyway?");
if (confirm == 0) {
try {
BufferedWriter writer = new BufferedWriter(
new FileWriter(file.getAbsolutePath()
+ ".rtf"));
writer.write(text);
writer.close();
} catch (IOException ex) {
ex.printStackTrace();
System.out.println(ex.getMessage());
JOptionPane.showMessageDialog(null,
"Failed to save the file");
}
}
else if (confirm == 1) {
JOptionPane.showMessageDialog(null,
"The file was not saved.");
}
}
}
if (option == JFileChooser.CANCEL_OPTION) {
saveFile.setVisible(false);
}
}// End of method
The only problem I've seen in your code is that you're not closing the output stream (when content is actually written to disk).
Try out.close().
It should solve your problem.

Categories