Make name to PDF with JFileChooser - java

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");

Related

Using ByteArrayOutputStream class to display Excel file but post download the excel file does not show colors as per logic

My issue is that I am using ByteArrayOutputStream class to display excel file with data and retrieved using toByteArray()
Issue: After I download the Excel file, the cells stops displaying required color after certain cells and I am unable to understand where it went wrong.
Code being used:
protected ByteArrayOutputStream createXLS(Map contextMap) throws FwkException {
long compteurLigne = 0;
// On cree un classeur
HSSFWorkbook wb = new HSSFWorkbook();
// Pour chaque poste, on cree une feuille
// On cree une feuille
HSSFSheet s = wb.createSheet();
// Creation entete de la feuille
creerEntete(wb, s, contextMap);
setTableHead(wb, s, contextMap);
List listePoste = (List) contextMap.get("list");
for (Iterator ite = listePoste.iterator(); ite.hasNext();) {
HypothesesCompararerOutillagePoste hypothesesCompararerOutillagePoste = (HypothesesCompararerOutillagePoste) ite.next();
creerLigneMatrice(hypothesesCompararerOutillagePoste, s, wb);
setTailleColonne(s);
}
ByteArrayOutputStream dataOut = new ByteArrayOutputStream();
try {
wb.write(dataOut);
} catch (IOException e) {
throw new TechnicalException("Error while writing the output to de workbook", e);
}
return dataOut;
}
Main Logic for colour being displayed in Excel file(xls):
private void setCsPplusOuMoinsOutillageColor(HSSFCellStyle csPplusOuMoinsOutillage, String plusOuMoinsOutillage) {
if (plusOuMoinsOutillage != null) {
if (plusOuMoinsOutillage.equals("-")) {
csPplusOuMoinsOutillage.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
csPplusOuMoinsOutillage.setFillForegroundColor(HSSFColor.RED.index);
} else if (plusOuMoinsOutillage.equals("+")) {
csPplusOuMoinsOutillage.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
csPplusOuMoinsOutillage.setFillForegroundColor(HSSFColor.LIGHT_GREEN.index);
} else {
csPplusOuMoinsOutillage.setFillPattern(HSSFCellStyle.NO_FILL);
}
}
}
Below is the code where data gets retrieved toByteArray():
protected void doEoxExecute() throws FwkException {
try {
Map contextMap = (Map) getInput(IN_CONTEXT_MAP);
String langue = (String) getInput(IN_LOCALE_LANGUAGE);
String pays = (String) getInput(IN_LOCALE_COUNTRY);
Collection<Object> listeMsg = (Collection) getInput(IN_LOGGER_MSG);
if (listeMsg != null && !listeMsg.isEmpty()) {
Iterator<Object> iter = listeMsg.iterator();
while (iter.hasNext()) {
Object msg = iter.next();
if (msg instanceof String)
batchlog.info((String) msg);
}
}
locale = null;
if (langue != null) {
if (pays != null)
locale = new Locale(langue, pays);
else
locale = new Locale(langue);
} else
locale = Locale.FRANCE;
boolean inSec = Boolean.parseBoolean((String) getInput(IN_TIME_IN_SEC));
EOXContext.setCtx(!inSec, locale);
ByteArrayOutputStream out = createXLS(contextMap);
byte[] xls = out.toByteArray();
// si aucune donnee, on affiche un message a l'utilisateur
if (xls == null) {
batchlog.info(getMessage(broker, "commun.export.xls.aucuneDonnee", locale));
} else {
String repertoireTemporaire = EoxBatchService.getPropriete(FICHIER_PROPERTIES, "GenererXlsDocPoste.io.temp", null);
if (repertoireTemporaire == null)
repertoireTemporaire = EoxBatchService.getPropriete(EoxConstants.FICHIER_PROPRIETES_SERVEUR, "GenererXlsDocPoste.io.temp", null);
if (repertoireTemporaire != null) {
File repertoire = new File(repertoireTemporaire);
File fichierXls = File.createTempFile("doc", ".xls", repertoire);
if (logger.isInfoEnabled())
logger.info("creation fichier XLS : " + fichierXls.getAbsolutePath());
FileOutputStream fos = new FileOutputStream(fichierXls);
fos.write(xls);
fos.flush();
fos.close();
Also I am attaching the output of the excel file which shows no colors after certain 35th cell:

I need to read an archive and apply an algoritm in it

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.

delete image from the folder

I want to delete one image from the folder when I delete a user from the table with this image. Here is my code:
//first I can the function that finds a path of the image in the folder
public void deleteStudent(String name) {
try {
CallableStatement statement = null;
Connection data = getmyConnection();
statement = data.prepareCall("{call delete_student(?)}");
statement.setString(1, name);
//statement.registerOutParameter(2, java.sql.Types.VARCHAR);
statement.executeQuery();
} catch (Exception c) {
c.printStackTrace();
}
//After I call the function to delete image from directory
deleteImageDerictory(name);
}
This method allows choosing the image from the directory when I get the image I add the path in jTextField1.getText().
//use this method to get the path of my image.
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
JFileChooser file = new JFileChooser();
file.setCurrentDirectory(new File(System.getProperty("user.home")));
FileNameExtensionFilter filter = new FileNameExtensionFilter("*.Images", "jpeg", "jpg", "png");
file.addChoosableFileFilter(filter);
int result = file.showSaveDialog(null);
if(result ==JFileChooser.APPROVE_OPTION) {
File selectedFile = file.getSelectedFile();
//GET ABSOLUTE PATH OF PICTURES
jTextField1.setText(selectedFile.getAbsolutePath());
//addPicture.setText(selectedFile.getName());
//GET NAME OF PICTURES
//getPicName = selectedFile.getName();
} else if(result == JFileChooser.CANCEL_OPTION) {
System.out.println("File not found!");
}
}
//I use this method to call another method deleteImageDerictory(jTextField1.getText());
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try{
deleteImageDerictory(jTextField1.getText());
}catch(Exception e) {
e.printStackTrace();
}
}
public void deleteImageDerictory(String name) {
String pictureName = null;
try {
CallableStatement statement = null;
Connection data = getmyConnection();
statement = data.prepareCall("{call get_picture(?)}");
statement.setString(1, name);
//statement.registerOutParameter(2, java.sql.Types.VARCHAR);
myResults = statement.executeQuery();
while (myResults.next()) {
//COPY PATH IN pictureName
pictureName = myResults.getString(1);
}
myResults.close();
} catch (Exception c) {
c.printStackTrace();
}
//DELETE ELEMENT FROM FOLDER
File sourceFile = new File(pictureName);
File file = new File("/Computer/NetBeans IDE 8.2/NewDataBase/src/newdatabase/images/");
images = file.listFiles();
File file2 = new File(file.getAbsolutePath(), sourceFile.getName() );
boolean deleted = file2.delete();
System.out.println(deleted);
}
I just don't know how to delete image from folder when I find it. Any ideas?
You can use the modern and more powerful java.nio.* instead of the old fashioned java.io.File. You just have to create a Path object containing the path to the folder where the images are stored and resolve the file name:
//DELETE ELEMENT FROM FOLDER
Path imagesPath = Paths.get(
"/Computer/NetBeans IDE 8.2/NewDataBase/src/newdatabase/images/" +
pictureName);
try {
Files.delete(imagesPath);
System.out.println("File "
+ imagesPath.toAbsolutePath().toString()
+ " successfully removed");
} catch (IOException e) {
System.err.println("Unable to delete "
+ imagesPath.toAbsolutePath().toString()
+ " due to...");
e.printStackTrace();
}
EDIT due to discussion in comments below:
This is a very simple approach that deletes a file chosen via JFileChooser:
public static void main(String[] args) {
JFileChooser jfc = new JFileChooser(FileSystemView.getFileSystemView().getHomeDirectory());
int result = jfc.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
File selectedFile = jfc.getSelectedFile();
System.out.println("Chosen file: " +
selectedFile.getAbsolutePath() +
" will be deleted!");
Path pathToBeDeleted = Paths.get(selectedFile.getAbsolutePath());
try {
Files.delete(pathToBeDeleted);
} catch (IOException e) {
e.printStackTrace();
}
}
}
I have just tried it myself and it successfully removes the chosen file.
public static void main(String[] args) {
JFileChooser jfc = new JFileChooser(FileSystemView.getFileSystemView()./0());
int result = jfc.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
File selectedFile = jfc.getSelectedFile();
System.out.println("Chosen file: " +
selectedFile.getAbsolutePath() +
" will be deleted!");
Path data= Paths.get(selectedFile.getAbsolutePath());
try {
Files.delete(data);
} catch (Exception e) {
e.printStackTrace();
}
}
}

Export/Download presentations and SpreadSheet impersonate other domain users with using administrative access

I need to export/download all files of the other domain users. I used the client login with administer account to see the all files of domain users. however,only document can be export/download,others are fail.
so what is the download url format of the others(For File,pdf,presentation and spreadsheet)??
my document download url is
https://docs.google.com/feeds/download/documents/Export?xoauth_requestor=admin#domain.com&docId=<id>&exportFormat=doc
my program is as following:
public class AuthExample {
private static DocsService docService = new DocsService("Auth Example");
public static void main(String[] args)
throws Exception
{
String adminUser = admin;
String adminPassword = adminpasswd;
String impersonatedUser = "user#domain.com";
docService.setUserCredentials(adminUser, adminPassword);
URL url = new URL( "https://docs.google.com/feeds/" + impersonatedUser + "/private/full");
DocumentListFeed feed = docService.getFeed(url, DocumentListFeed.class);
for (DocumentListEntry entry : feed.getEntries()) {
String title = entry.getTitle().getPlainText();
System.out.println( title );
String type = entry.getType();
if ( type.equals("document") )
{
String encodedAdminUser = URLEncoder.encode(adminUser);
String resourceId = entry.getResourceId();
String resourceIdNoPrefix = resourceId.substring( resourceId.indexOf(':')+1 );
String downloadUrl =
"https://docs.google.com/feeds/download/documents/Export" +
"?xoauth_requestor=" + encodedAdminUser +
"&docId=" + resourceIdNoPrefix +
"&exportFormat=doc";
downloadFile( downloadUrl, title + ".doc" );
}
}
}
// Method pasted directly from Google documentation
public static void downloadFile(String exportUrl, String filepath)
throws IOException, MalformedURLException, ServiceException
{
System.out.println("Exporting document from: " + exportUrl);
MediaContent mc = new MediaContent();
mc.setUri(exportUrl);
MediaSource ms = docService.getMedia(mc);
InputStream inStream = null;
FileOutputStream outStream = null;
try {
inStream = ms.getInputStream();
outStream = new FileOutputStream(filepath);
int c;
while ((c = inStream.read()) != -1) {
outStream.write(c);
}
} finally {
if (inStream != null) {
inStream.close();
}
if (outStream != null) {
outStream.flush();
outStream.close();
}
}
}
}
Don't build the download link manually, instead use the entry's content link as explained in the docs:
https://developers.google.com/google-apps/documents-list/#downloading_documents_and_files

how to open file with specific extension in fileDialogue

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);

Categories