I am trying to Open a file with specific extension ( .fcg or .wtg ) using file Dialog
is there a way to do it ??
If you can use JFileChooser you can use JFileChooser.addChoosableFileFilter() to filter files by extension.
JFileChooser fileChooser = new JFileChooser();
fileChooser.addChoosableFileFilter(new FileFilter() {
#Override
public String getDescription() {
return "*.fct, *.wtg";
}
#Override
public boolean accept(File f) {
return f.getName().endsWith(".fcg") ||
f.getName().endsWith(".wtg");
}
});
You can use this this code to choose a file and read
public void openFile() throws Exception {
int rowCount = 0;
int rowNo = 2;
String id = "";
String name = "";
JFileChooser fc = new JFileChooser();
int result = fc.showOpenDialog(new JPanel());
if (result == JFileChooser.APPROVE_OPTION) {
String file = String.valueOf(fc.getSelectedFile());
File fil = new File(file);
System.out.println("File Selected" + file);
FileInputStream fin = new FileInputStream(fil);
int ch;
while ((ch = fin.read()) != -1) {
System.out.print((char)ch);
}
} else {
}
}
As this is google search #1 for me, this is the solution which worked best for me:
How to restrict file choosers in java to specific files
specifics:
JFileChooser open = new JFileChooser(openPath);
FileNameExtensionFilter filter = new FileNameExtensionFilter("PLSQL Files", "sql", "prc", "fnc", "pks"
, "pkb", "trg", "vw", "tps" , "tpb");
open.setFileFilter(filter);
Related
I'm working on an app that read an archive(.txt exclusively) via JFileChooser. The thing that I need is that have an algorithm (KMP, BM) to find in the archive the app is reading, patterns that match the KMP and BM algorithm def.
I have this method to read archives:
public void Lectura() {
Scanner entrada = null;
JFileChooser fileChooser = new JFileChooser(".");
FileFilter filtro = new FileNameExtensionFilter("Archivos txt (.txt)", "txt");
fileChooser.setFileFilter(filtro);
int valor = fileChooser.showOpenDialog(fileChooser);
if (valor == JFileChooser.APPROVE_OPTION) {
String ruta = fileChooser.getSelectedFile().getAbsolutePath();
try {
File f = new File(ruta);
entrada = new Scanner(f);
while (entrada.hasNext()) {
System.out.println(entrada.nextLine());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (entrada != null) {
entrada.close();
}
}
} else {
System.out.println("No se ha seleccionado ningĂșn fichero");
}
}
As I told you before I need this to work with the archive and the algorithms and I need the patterns to highlight the matching patterns, my question is how to work with the archive directly in the methods.
public class KMP {
Main m;
public KMP() {
m = new Main();
}
public void Kmp() {
String txt = "I need here the archive";
String pat = m.vent.pal.getText();;
int[] next = new int[pat.length()];
getNext(pat, next);
System.out.println(Search(txt, pat, next));
}
}
This is one of the algorithms, just the reading part.
I cant get jfilechooser to show the files I return from FileNameFilter. It still shows me all the files inside the folder. I believe fileChooser.setSelectedFiles(listOfMatchingFiles); should set what contents are displayed. I've searched the net but have only found examples of how to set what type of file extensions are viewable. Any help is appreciated. Thanks
final String[] currSelection = selecName.split("_");
FilenameFilter fileNames = new FilenameFilter() {
public boolean accept(File dir, String name) {
if (name.startsWith(currSelection[0])) {
return true;
} else {
return false;
}
}
};
JFileChooser fileChooser = new JFileChooser();
File[] listOfMatchingFiles = fileLOcation.listFiles(fileNames);
fileChooser.setCurrentDirectory(fileLOcation);
fileChooser.setSelectedFiles(listOfMatchingFiles);
for (File a : listOfMatchingFiles) {
//displays the set of files according to currSelection[0]
System.out.println(a);
}
fileChooser.setDialogTitle(currSelection[0]);
if (fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
File fileToVIEW = fileChooser.getSelectedFile();
}
I found here: what I was searching for but still I have some issues.
This is my action code:
private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) throws IOException {
jEditorPane1.setContentType("text/html");
int returnVal = FileChooser1.showOpenDialog(this);
if (returnVal == FileChooser1.APPROVE_OPTION) {
String image = String.format("<img src=\"%s\">", FileChooser1.getSelectedFile());
jEditorPane1.setText(image);
}
}
Here is a screenshot of what happens, as you can see the image is not loaded.
http://postimg.org/image/agc665ih1/
But if I save the file (with save button) and reopen the same file (with open button), the image is there and is perfectly loaded.
I already tried the .repaint() and .revalidate() methods, but is not working..
Any idea?
This may be problem in setting up path in JEditorPane page. use this:
String image = String.format("<img src=\"%s\">", FileChooser1.getSelectedFile().getPath());
I am assuming that you have already selected appropriate editorKit for JEditorPane.
So now I can answer with my code. I am using this class for the file chooser:
import java.io.File;
import javax.swing.filechooser.FileFilter;
class jpgfilter extends FileFilter {
public boolean accept(File file) {
return file.isDirectory() || file.getAbsolutePath().endsWith(".jpg");
}
public String getDescription() {
return "JPG image (*.jpg)";
}
}
And in my main class I have this:
FileChooser1 = new javax.swing.JFileChooser();
FileChooser1.setDialogTitle("Choose your image:");
FileChooser1.setFileFilter(new jpgfilter());
And that's it.
So I actually found some kind of a solution but I think there is really too much code and that I should do it easily..I actually insert the image and simultaneously save and open the content of the EditorPane as .html file.
The code:
jEditorPane1.setContentType("text/html");
int returnVal = FileChooser1.showOpenDialog(this);
if (returnVal == FileChooser1.APPROVE_OPTION) {
String image = String.format("<img src=\"%s\">", FileChooser1
.getSelectedFile().getPath());
jEditorPane1.setText(image);
String type = jEditorPane1.getContentType();
OutputStream os = new BufferedOutputStream(new FileOutputStream(
"/Library/java_test/temp" + ".html"));
Document doc = jEditorPane1.getDocument();
int length = doc.getLength();
if (type.endsWith("/rtf")) {
// Saving RTF - use the OutputStream
try {
jEditorPane1.getEditorKit().write(os, doc, 0, length);
os.close();
} catch (BadLocationException ex) {
}
} else {
// Not RTF - use a Writer.
Writer w = new OutputStreamWriter(os);
jEditorPane1.write(w);
w.close();
}
String url = "file:///" + "/Library/java_test/temp" + ".html";
jEditorPane1.setPage(url);
}
i use this code to save a pdf file on desktop from Mysql, but the file saved without extension, how can i save it automatcly with extension pdf, ?!!
JFileChooser JFileChooser = new JFileChooser(".");
Activiter ac = new Activiter();
int status = JFileChooser.showDialog(null,"Saisir l'emplacement et le nom du fichier cible");
if(status == JFileChooser.APPROVE_OPTION)
{
try
{
ac.chargeIMG(jTable3.getValueAt(rec, 6).toString(),JFileChooser.getSelectedFile().getAbsolutePath());
}
catch(Exception ex)
{
JOptionPane.showMessageDialog(null,"Une erreur s'est produite dans le chargement de documents.");
ex.printStackTrace();
}
}
thanks for Help,
methode chargerIMG that colled by ac.chargeIMG
chargeIMG is give the pdf file from MySQL, the code is
public void chargeIMG(String idpro, String location) throws Exception
{
// cnx
File monImage = new File(location);
FileOutputStream ostreamImage = new FileOutputStream(monImage);
try {
PreparedStatement ps = conn.prepareStatement("SELECT img FROM projet WHERE idpro=?");
try
{
ps.setString(1,idpro);
ResultSet rs = ps.executeQuery();
try
{
if(rs.next())
{
InputStream istreamImage = rs.getBinaryStream("img");
byte[] buffer = new byte[1024];
int length = 0;
while((length = istreamImage.read(buffer)) != -1)
{
ostreamImage.write(buffer, 0, length);
}
}
}
finally
{
rs.close();
}
}
finally
{
ps.close();
}
}
finally
{
ostreamImage.close();
}
}
Override getSelectedFile():
import java.io.File;
import javax.swing.JFileChooser;
public class MyFileChooser extends JFileChooser
{
private static final long serialVersionUID = 1L;
private String extension;
public MyFileChooser(String currentDirectoryPath, String extension)
{
super(currentDirectoryPath);
this.extension = extension;
}
#Override
public File getSelectedFile()
{
File selectedFile = super.getSelectedFile();
if(selectedFile != null && (getDialogType() == SAVE_DIALOG || getDialogType() == CUSTOM_DIALOG))
{
String name = selectedFile.getName();
if(!name.contains(".")) selectedFile = new File(selectedFile.getParentFile(), name + "." + extension);
}
return selectedFile;
}
}
and then use it like:
JFileChooser chooser = new MyFileChooser(".", "pdf");
The simplest solution, obtain the path (File.getPath), check if it ends by the expected extension and if not then replace it by another File with the extension present: new File(path+".pdf");
As the title states, is there a way to select multiple directories at once (all sub-directories immediately within a primary directory) with JFileChooser so I don't have to re-open the file chooser window for each directory?
Once again I've solved my own question after asking it.
The thing that was preventing me from getting it to work previously was I was using the check for multi-select rather than the set for multi-select, and apparently was using that wrong as well as I kept getting an error. Anyway, the working version is below:
class AddDirectory implements ActionListener {
public void actionPerformed(ActionEvent ae) {
File[] theDir = null;
theDir = selectDir();
if(theDir != null) {
for(File z : theDir) {
String[] curRow = { z.toString(), "Waiting"};
dlm.addRow(curRow);
}
}
return;
}
private File[] selectDir() {
JFileChooser fileChooser = new JFileChooser(lastDir);
fileChooser.setMultiSelectionEnabled(true);
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int showOpenDialog = fileChooser.showOpenDialog(null);
if (showOpenDialog != JFileChooser.APPROVE_OPTION) {
return null;
}
File[] uploadDir = fileChooser.getSelectedFiles();
lastDir = new File(uploadDir[uploadDir.length-1].getParent());
return uploadDir;
}
}
Once I get the directories, they're loaded into a JTable to be modified before running the rest of my code on them.