Search Results

Search found 8 results on 1 pages for 'getabsolutefile'.

Page 1/1 | 1 

  • Java JFileChooser getAbsoluteFile Add File Extension

    - by ikurtz
    i have this issue working but i would like to know if there is a better way of adding the file extension? what i am doing right now is: String filePath = chooser.getSelectedFile().getAbsoluteFile() + ".html"; im adding the extension hard coded. and then saving to it. just wondering if there is a more robust/logical manner this can be implemented? thank you for your time. EDIT: i ask this as i would like my app to be portable across platforms. so adding .html manually i may make this a windows only solution.

    Read the article

  • Tip #13 java.io.File Surprises

    - by ByronNevins
    There is an assumption that I've seen in code many times that is totally wrong.  And this assumption can easily bite you.  The assumption is: File.getAbsolutePath and getAbsoluteFile return paths that are not relative.  Not true!  Sort of.  At least not in the way many people would assume.  All they do is make sure that the beginning of the path is absolute.  The rest of the path can be loaded with relative path elements.  What do you think the following code will print? public class Main {    public static void main(String[] args) {        try {            File f = new File("/temp/../temp/../temp/../");            File abs  = f.getAbsoluteFile();            File parent = abs.getParentFile();            System.out.println("Exists: " + f.exists());            System.out.println("Absolute Path: " + abs);            System.out.println("FileName: " + abs.getName());            System.out.printf("The Parent Directory of %s is %s\n", abs, parent);            System.out.printf("The CANONICAL Parent Directory of CANONICAL %s is %s\n",                        abs, abs.getCanonicalFile().getParent());            System.out.printf("The CANONICAL Parent Directory of ABSOLUTE %s is %s\n",                        abs, parent.getCanonicalFile());            System.out.println("Canonical Path: " + f.getCanonicalPath());        }        catch (IOException ex) {            System.out.println("Got an exception: " + ex);        }    }} Output: Exists: trueAbsolute Path: D:\temp\..\temp\..\temp\..FileName: ..The Parent Directory of D:\temp\..\temp\..\temp\.. is D:\temp\..\temp\..\tempThe CANONICAL Parent Directory of CANONICAL D:\temp\..\temp\..\temp\.. is nullThe CANONICAL Parent Directory of ABSOLUTE D:\temp\..\temp\..\temp\.. is D:\tempCanonical Path: D:\ Notice how it says that the parent of d:\ is d:\temp !!!The file, f, is really the root directory.  The parent is supposed to be null. I learned about this the hard way! getParentXXX simply hacks off the final item in the path. You can get totally unexpected results like the above. Easily. I filed a bug on this behavior a few years ago[1].   Recommendations: (1) Use getCanonical instead of getAbsolute.  There is a 1:1 mapping of files and canonical filenames.  I.e each file has one and only one canonical filename and it will definitely not have relative path elements in it.  There are an infinite number of absolute paths for each file. (2) To get the parent file for File f do the following instead of getParentFile: File parent = new File(f, ".."); [1] http://bt2ws.central.sun.com/CrPrint?id=6687287

    Read the article

  • Java Desktop app with Ms Access.

    - by zayar
    My Db connection is error "class not found exception!". I want to show in java jTable with query result.. static Connection databaseConnection()throws ClassNotFoundException{ Connection con=null; File file=new File("PlayDb/PlayIS.mdb"); try{ Class.forName("sun.jdbc.odbc.jdbcodbcDriver"); con =DriverManager.getConnection("jdbc:odbc:Driver="+"{Microsoft Access Driver(*.mdb,*.accdb)};DBQ="+file.getAbsoluteFile()); System.out.print("Success con!!"); } catch(Exception e){ System.out.print("connection fail!!"); e.printStackTrace(); } return con; }

    Read the article

  • Robotium - Write to file in eclipse workspace or computer file system

    - by Flavio Capaccio
    I'm running some tests using Robotium on an Android application that interacts with a web-portal. I'd like to save some information to file; for example I need to save the id of the username I created from the app and I want to make it read from Selenium to run tests on web-portal to verify a webpage for that user has been created. Is it possible? Could someone suggest me a solution or a work-around? This is an example of code, but it doesn't work (I want to write to a file for example on c:\myworkspace\filename.txt a string): public void test_write_file(){ if(!solo.searchText("HOME")){ signIn("39777555333", VALID_PASSWORD); } try { String content = "This is the content to write into file"; File file = new File("filename.txt"); // if file doesnt exists, then create it if (!file.exists()) { file.createNewFile(); } FileWriter fw = new FileWriter(file.getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw); bw.write(content); bw.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } assertTrue(solo.searchText("HOME")); }

    Read the article

  • Synchronous Android activities

    - by rayman
    Ive made mis-leading topic in my last question, so i open this new question to clear what I realy want. sorry for the inconvenience. I wanna run two system(Android) activities one after another in specific order from my main activity. now as we know, startActivity is an asynchronous operation, so i cant keep on a specific order. so i thought maybe I should try to do it with dialogBox in the middle but also running a dialogBox is an asynchronous. now as i said the activities which i try to run are Android activities, so i cant even start them with startActivityForResult (or mybe i can, but i dont get any result back to my main(calling) activity) Any tricks how could i manage with this issue? Some code: first activity: Intent intent = new Intent(); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setAction(Settings.ACTION_APPLICATION_SETTINGS); startActivity(intent); second activity: Intent intent = new Intent(Intent.ACTION_VIEW); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setDataAndType(Uri.fromFile(tmpPackageFile .getAbsoluteFile()), "application/vnd.android.package-archive"); startActivity(intent); as you can see, i dont have any access to those activites, i can just run thire intents from my main activity.

    Read the article

  • Converting text into numeric in xls using Java

    - by Work World
    When I create excel sheet through java ,the column which has number datatype in the oracle table, get converted to text format in excel.I want it to remain in the number format.Below is my code snippet for excel creation. FileWriter fw = new FileWriter(tempFile.getAbsoluteFile(),true); // BufferedWriter bw = new BufferedWriter(fw); HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet sheet = wb.createSheet("Excel Sheet"); //Column Size of excel for(int i=0;i<10;i++) { sheet.setColumnWidth((short) i, (short)8000); } String userSelectedValues=result; HSSFCellStyle style = wb.createCellStyle(); ///HSSFDataFormat df = wb.createDataFormat(); style.setFillForegroundColor(HSSFColor.GREY_25_PERCENT.index); style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); //style.setDataFormat(df.getFormat("0")); HSSFFont font = wb.createFont(); font.setColor(HSSFColor.BLACK.index); font.setBoldweight((short) 700); style.setFont(font); int selecteditems=userSelectedValues.split(",").length; // HSSFRow rowhead = sheet.createRow((short)0); //System.out.println("**************selecteditems************" +selecteditems); for(int k=0; k<selecteditems;k++) { HSSFRow rowhead = sheet.createRow((short)k); if(userSelectedValues.contains("O_UID")) { HSSFCell cell0 = rowhead.createCell((short) k); cell0.setCellValue("O UID"); cell0.setCellStyle(style); k=k+1; } ///some columns here.. } int index=1; for (int i = 0; i<dataBeanList.size(); i++) { odb=(OppDataBean)dataBeanList.get(i); HSSFRow row = sheet.createRow((short)index); for(int j=0;j<selecteditems;j++) { if(userSelectedValues.contains("O_UID")) { row.createCell((short)j).setCellValue(odb.getUID()); j=j+1; } } index++; } FileOutputStream fileOut = null; try { fileOut = new FileOutputStream(path.toString()+"/temp.xls"); } catch (FileNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { wb.write(fileOut); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } try { fileOut.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }

    Read the article

  • Logcat error: "addView(View, LayoutParams) is not supported in AdapterView" in a ListView

    - by HacKreatorz
    I'm doing an aplication for Android and something I need is that it shows a list of all files and directories in the SD Card and it has to be able to move through the different directories. I found a good tutorial in anddev: http://bit.ly/h4GyFC I modified a few things so the aplication moves in the SD Card and not in Android root Directories but the rest is mostly the same. This is my xml file for the activity: <?xml version="1.0" encoding="utf-8"?> <ListView xmlns:android="http://schemas.android.com/apk/res/android" android:id="@id/android:list" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" /> </ListView> And this is the code for the Activity: import hackreatorz.cifrador.R; import java.io.File; import java.util.ArrayList; import android.app.ListActivity; import android.content.res.Configuration; import android.os.Bundle; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; public class ArchivosSD extends ListActivity { private ArrayList<String> directoryEntries = new ArrayList<String>(); private File currentDirectory = new File("/sdcard/"); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); browseToSD(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); } private void browseToSD() { browseTo(new File("/sdcard/")); } private void upOneLevel() { if(this.currentDirectory.getParent() != null) this.browseTo(this.currentDirectory.getParentFile()); } private void browseTo(final File directory) { if (directory.isDirectory()) { this.currentDirectory = directory; fill(directory.listFiles()); } else { Toast.makeText(ArchivosSD.this, this.directoryEntries.get(this.getSelectedItemPosition()), Toast.LENGTH_SHORT).show(); } } private void fill(File[] files) { this.directoryEntries.clear(); this.directoryEntries.add(getString(R.string.current_dir)); if(this.currentDirectory.getParent() != null) this.directoryEntries.add(getString(R.string.up_one_level)); int currentPathStringLength = (int) this.currentDirectory.getAbsoluteFile().length(); for (File file : files) { this.directoryEntries.add(file.getAbsolutePath().substring(currentPathStringLength)); } setListAdapter(new ArrayAdapter<String>(this, R.layout.archivos_sd, this.directoryEntries)); } @Override protected void onListItemClick(ListView l, View v, int position, long id) { int selectionRowID = (int) this.getSelectedItemPosition(); String selectedFileString = this.directoryEntries.get(selectionRowID); if (selectedFileString.equals(".")) { this.browseToSD(); } else if(selectedFileString.equals("..")) { this.upOneLevel(); } else { File clickedFile = null; clickedFile = new File(this.currentDirectory.getAbsolutePath() + this.directoryEntries.get(selectionRowID)); if(clickedFile != null) this.browseTo(clickedFile); } } } I don't get any errores in Eclipse, but I get a Force Close when running the aplication on my phone and when I look at Logcat I see the following: 01-01 23:30:29.858: ERROR/AndroidRuntime(14911): FATAL EXCEPTION: main *01-01 23:30:29.858: ERROR/AndroidRuntime(14911): java.lang.UnsupportedOperationException: addView(View, LayoutParams) is not supported in AdapterView* I don't have a clue what to do, I've looked up in Google and I didn't find anything and I did the same at stackoverflow. This is my first aplication in Java and for Android so I'm a real n00b and if the answer was there, I didn't understand it so I would really apreciate if you could explain what I should do to fix this error and why. Thanks for everything in advanced.

    Read the article

  • Java JTextPane JScrollPane Display Issue

    - by ikurtz
    The following class implements a chatGUI. When it runs okay the screen looks like this: Fine ChatGUI The problem is very often when i enter text of large length ie. 50 - 100 chars the gui goes crazy. the chat history box shrinks as shown in this image. Any ideas regarding what is causing this? Thank you. package Sartre.Connect4; import javax.swing.*; import java.net.*; import java.awt.*; import java.awt.event.*; import javax.swing.text.StyledDocument; import javax.swing.text.Style; import javax.swing.text.StyleConstants; import javax.swing.text.BadLocationException; import java.io.BufferedOutputStream; import javax.swing.text.html.HTMLEditorKit; import java.io.FileOutputStream; import java.io.IOException; import java.io.FileNotFoundException; import javax.swing.filechooser.FileNameExtensionFilter; import javax.swing.JFileChooser; /** * Chat form class * @author iAmjad */ public class ChatGUI extends JDialog implements ActionListener { /** * Used to hold chat history data */ private JTextPane textPaneHistory = new JTextPane(); /** * provides scrolling to chat history pane */ private JScrollPane scrollPaneHistory = new JScrollPane(textPaneHistory); /** * used to input local message to chat history */ private JTextPane textPaneHome = new JTextPane(); /** * Provides scrolling to local chat pane */ private JScrollPane scrollPaneHomeText = new JScrollPane(textPaneHome); /** * JLabel acting as a statusbar */ private JLabel statusBar = new JLabel("Ready"); /** * Button to clear chat history pane */ private JButton JBClear = new JButton("Clear"); /** * Button to save chat history pane */ private JButton JBSave = new JButton("Save"); /** * Holds contentPane */ private Container containerPane; /** * Layout GridBagLayout manager */ private GridBagLayout gridBagLayout = new GridBagLayout(); /** * GridBagConstraints */ private GridBagConstraints constraints = new GridBagConstraints(); /** * Constructor for ChatGUI */ public ChatGUI(){ setTitle("Chat"); // set up dialog icon URL url = getClass().getResource("Resources/SartreIcon.jpg"); ImageIcon imageIcon = new ImageIcon(url); Image image = imageIcon.getImage(); this.setIconImage(image); this.setAlwaysOnTop(true); setLocationRelativeTo(this.getParent()); //////////////// End icon and placement ///////////////////////// // Get pane and set layout manager containerPane = getContentPane(); containerPane.setLayout(gridBagLayout); ///////////////////////////////////////////////////////////// //////////////// Begin Chat History ////////////////////////////// textPaneHistory.setToolTipText("Chat History Window"); textPaneHistory.setEditable(false); textPaneHistory.setPreferredSize(new Dimension(350,250)); scrollPaneHistory.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); scrollPaneHistory.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); // fill Chat History GridBagConstraints constraints.gridx = 0; constraints.gridy = 0; constraints.gridwidth = 10; constraints.gridheight = 10; constraints.weightx = 100; constraints.weighty = 100; constraints.fill = GridBagConstraints.BOTH; constraints.anchor = GridBagConstraints.CENTER; constraints.insets = new Insets(10,10,10,10); constraints.ipadx = 0; constraints.ipady = 0; gridBagLayout.setConstraints(scrollPaneHistory, constraints); // add to the pane containerPane.add(scrollPaneHistory); /////////////////////////////// End Chat History /////////////////////// ///////////////////////// Begin Home Chat ////////////////////////////// textPaneHome.setToolTipText("Home Chat Message Window"); textPaneHome.setPreferredSize(new Dimension(200,50)); textPaneHome.addKeyListener(new MyKeyAdapter()); scrollPaneHomeText.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS); scrollPaneHomeText.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); // fill Chat History GridBagConstraints constraints.gridx = 0; constraints.gridy = 10; constraints.gridwidth = 6; constraints.gridheight = 1; constraints.weightx = 100; constraints.weighty = 100; constraints.fill = GridBagConstraints.BOTH; constraints.anchor = GridBagConstraints.CENTER; constraints.insets = new Insets(10,10,10,10); constraints.ipadx = 0; constraints.ipady = 0; gridBagLayout.setConstraints(scrollPaneHomeText, constraints); // add to the pane containerPane.add(scrollPaneHomeText); ////////////////////////// End Home Chat ///////////////////////// ///////////////////////Begin Clear Chat History //////////////////////// JBClear.setToolTipText("Clear Chat History"); // fill Chat History GridBagConstraints constraints.gridx = 6; constraints.gridy = 10; constraints.gridwidth = 2; constraints.gridheight = 1; constraints.weightx = 100; constraints.weighty = 100; constraints.fill = GridBagConstraints.BOTH; constraints.anchor = GridBagConstraints.CENTER; constraints.insets = new Insets(10,10,10,10); constraints.ipadx = 0; constraints.ipady = 0; gridBagLayout.setConstraints(JBClear, constraints); JBClear.addActionListener(this); // add to the pane containerPane.add(JBClear); ///////////////// End Clear Chat History //////////////////////// /////////////// Begin Save Chat History ////////////////////////// JBSave.setToolTipText("Save Chat History"); constraints.gridx = 8; constraints.gridy = 10; constraints.gridwidth = 2; constraints.gridheight = 1; constraints.weightx = 100; constraints.weighty = 100; constraints.fill = GridBagConstraints.BOTH; constraints.anchor = GridBagConstraints.CENTER; constraints.insets = new Insets(10,10,10,10); constraints.ipadx = 0; constraints.ipady = 0; gridBagLayout.setConstraints(JBSave, constraints); JBSave.addActionListener(this); // add to the pane containerPane.add(JBSave); ///////////////////// End Save Chat History ///////////////////// /////////////////// Begin Status Bar ///////////////////////////// constraints.gridx = 0; constraints.gridy = 11; constraints.gridwidth = 10; constraints.gridheight = 1; constraints.weightx = 100; constraints.weighty = 50; constraints.fill = GridBagConstraints.BOTH; constraints.anchor = GridBagConstraints.CENTER; constraints.insets = new Insets(0,10,5,0); constraints.ipadx = 0; constraints.ipady = 0; gridBagLayout.setConstraints(statusBar, constraints); // add to the pane containerPane.add(statusBar); ////////////// End Status Bar //////////////////////////// // set resizable to false this.setResizable(false); // pack the GUI pack(); } /** * Deals with necessary menu click events * @param event */ public void actionPerformed(ActionEvent event) { Object source = event.getSource(); // Process Clear button event if (source == JBClear){ textPaneHistory.setText(null); statusBar.setText("Chat History Cleared"); } // Process Save button event if (source == JBSave){ // process only if there is data in history pane if (textPaneHistory.getText().length() > 0){ // process location where to save the chat history file JFileChooser chooser = new JFileChooser(); chooser.setMultiSelectionEnabled(false); chooser.setAcceptAllFileFilterUsed(false); FileNameExtensionFilter filter = new FileNameExtensionFilter("HTML Documents", "htm", "html"); chooser.setFileFilter(filter); int option = chooser.showSaveDialog(ChatGUI.this); if (option == JFileChooser.APPROVE_OPTION) { // Set up document to be parsed as HTML StyledDocument doc = (StyledDocument)textPaneHistory.getDocument(); HTMLEditorKit kit = new HTMLEditorKit(); BufferedOutputStream out; try { // add final file name and extension String filePath = chooser.getSelectedFile().getAbsoluteFile() + ".html"; out = new BufferedOutputStream(new FileOutputStream(filePath)); // write out the HTML document kit.write(out, doc, doc.getStartPosition().getOffset(), doc.getLength()); } catch (FileNotFoundException e) { JOptionPane.showMessageDialog(ChatGUI.this, "Application will now close. \n A restart may cure the error!\n\n" + e.getMessage(), "Fatal Error", JOptionPane.WARNING_MESSAGE, null); System.exit(2); } catch (IOException e){ JOptionPane.showMessageDialog(ChatGUI.this, "Application will now close. \n A restart may cure the error!\n\n" + e.getMessage(), "Fatal Error", JOptionPane.WARNING_MESSAGE, null); System.exit(3); } catch (BadLocationException e){ JOptionPane.showMessageDialog(ChatGUI.this, "Application will now close. \n A restart may cure the error!\n\n" + e.getMessage(), "Fatal Error", JOptionPane.WARNING_MESSAGE, null); System.exit(4); } statusBar.setText("Chat History Saved"); } } } } /** * Process return key for sending the message */ private class MyKeyAdapter extends KeyAdapter { @Override @SuppressWarnings("static-access") public void keyPressed(KeyEvent ke) { DateTime dateTime = new DateTime(); String nowdateTime = dateTime.getDateTime(); int kc = ke.getKeyCode(); if (kc == ke.VK_ENTER) { try { // Process only if there is data if (textPaneHome.getText().length() > 0){ // Add message origin formatting StyledDocument doc = (StyledDocument)textPaneHistory.getDocument(); Style style = doc.addStyle("HomeStyle", null); StyleConstants.setBold(style, true); String home = "Home [" + nowdateTime + "]: "; doc.insertString(doc.getLength(), home, style); StyleConstants.setBold(style, false); doc.insertString(doc.getLength(), textPaneHome.getText() + "\n", style); // update caret location textPaneHistory.setCaretPosition(doc.getLength()); textPaneHome.setText(null); statusBar.setText("Message Sent"); } } catch (BadLocationException e) { JOptionPane.showMessageDialog(ChatGUI.this, "Application will now close. \n A restart may cure the error!\n\n" + e.getMessage(), "Fatal Error", JOptionPane.WARNING_MESSAGE, null); System.exit(1); } ke.consume(); } } } }

    Read the article

1