create new word document from java - java

I want to open New MS Word Document to open on button click in java
can you suggest me the code , I am doing this by following code but i think its to open the existing document not to create the new document
class OpenWordFile {
public static void main(String args[]) {
try {
Runtime rt = Runtime.getRuntime();
rt.exec("cmd.exe /C start Employee.doc");
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Exception occured" + ex);
}
}
}

You can not do this using Java alone, at least if you need to generate DOC Files you need a 3rd tool library Aspose for example. Take a look at this thread, otherwise you can open existing files using the runtime.

only the comment with out any words
Runtime run = Runtime.getRuntime();
String lcOSName = System.getProperty("os.name").toLowerCase();
boolean MAC_OS_X = lcOSName.startsWith("mac os x");
if (MAC_OS_X) {
run.exec("open " + file);
} else {
//run.exec("cmd.exe /c start " + file); //win NT, win2000
run.exec("rundll32 url.dll, FileProtocolHandler " + path);
}

In the recent release (Java 6.0), Java provides Desktop class. The purpose of the class is to open the application in your system that is associated with the given file. So, if you invoke open() method with a Word document (.doc) then it automatically invokes MS Word as that is the application associated with .doc files.
I have developed a small Swing program (though you can develop it as a console application) to take document number from user and invoke document into MSWord. The assumption is; documents are stored with filename consisting of <document number>>.doc.
Given below is the Java program that you can compile and run it as-it-is. Make sure you change DIR variable to the folder where .doc files are stored.
Here is the code to open Word Doc in Java... its an extract from net....
import java.io.File;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
public class WordDocument extends JFrame {
private JButton btnOpen;
private JLabel jLabel1;
private JTextField txtDocNumber;
private static String DIR ="c:\\worddocuments\\"; // folder where word documents are present.
public WordDocument() {
super("Open Word Document");
initComponents();
}
private void initComponents() {
jLabel1 = new JLabel();
txtDocNumber = new JTextField();
btnOpen = new JButton();
Container c = getContentPane();
c.setLayout(new java.awt.FlowLayout());
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("Enter Document Number : ");
c.add(jLabel1);
txtDocNumber.setColumns(5);
c.add(txtDocNumber);
btnOpen.setText("Open Document");
btnOpen.addActionListener(new ActionListener() { // anonymous inner class
public void actionPerformed(ActionEvent evt) {
Desktop desktop = Desktop.getDesktop();
try {
File f = new File( DIR + txtDocNumber.getText() + ".doc");
desktop.open(f); // opens application (MSWord) associated with .doc file
}
catch(Exception ex) {
// WordDocument.this is to refer to outer class's instance from inner class
JOptionPane.showMessageDialog(WordDocument.this,ex.getMessage(),"Error", JOptionPane.ERROR_MESSAGE);
}
}
});
c.add(btnOpen);
} // initCompnents()
public static void main(String args[]) {
WordDocument wd = new WordDocument();
wd.setSize(300,100);
wd.setVisible(true);
}
}

Maybe using java.awt.Desktop can help?
File f = new File("<some temp path>\\file.docx");
f.createNewFile();
Desktop.getDesktop().open(f);
Creates a new empty document and opens it with the systsem specifik program for the extension. The strength of this solution is that it works for all OS... As long as the OS has a program to view the file that is.
Although I suspect that you are looking for semthing with abit more control over the creation of the file...

Related

is it possible to read the downloaded file from chrome browser using selenium

I downloaded a text file by a click button functionality, using Selenium Java.
then the file is downloaded to a particular location in the system, for example,
C://myAppfiles.
But I can't access that downloaded folder because of some reason. But I have to read that file while downloading.
How to do it? is it possible to read that file from the browser(chrome) using selenium or any other method is available?
so I'd suggest to do the following:
wait until file download is done completely.
After that- try to list all the files in the given directory:
all files inside folder and sub-folder
public static void main(String[]args)
{
File curDir = new File(".");
getAllFiles(curDir);
}
private static void getAllFiles(File curDir) {
File[] filesList = curDir.listFiles();
for(File f : filesList){
if(f.isDirectory())
getAllFiles(f);
if(f.isFile()){
System.out.println(f.getName());
}
}
}
files/folder only
public static void main(String[]args)
{
File curDir = new File(".");
getAllFiles(curDir);
}
private static void getAllFiles(File curDir) {
File[] filesList = curDir.listFiles();
for(File f : filesList){
if(f.isDirectory())
System.out.println(f.getName());
if(f.isFile()){
System.out.println(f.getName());
}
}
}
That will help You to understand if there any files at all (in the given directory).
Dont forget to make paths platform independent (to the folder/ file), like:
//platform independent and safe to use across Unix and Windows
File fileSafe = new File("tmp"+File.separator+"myDownloadedFile.txt");
Also, You might want to check whether file actually exists via Path methods.
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Main {
public static void main(String[] args) throws Exception {
Path filePath= Paths.get("C:\\myAppfiles\\downloaded.txt");
System.out.println("if exists: " + Files.exists(firstPath));
}
}
Additionally, path suggests You to check some other options on the file:
The following code snippet verifies that a particular file exists and that the program has the ability to execute the file.
Path file = ...;
boolean isRegularExecutableFile = Files.isRegularFile(file) &
Files.isReadable(file) & Files.isExecutable(file);
Once You face any exception- feel free to post it here.
Hope this helps You

Trouble with jar file and image

I have coded a program in Eclipse and it works properly when I run in that.
public static void initialize() throws IOException{
JTextField tfQrText;
int size = 250;
File qrFile;
BufferedImage qrBufferedImage;
JFrame gui = new JFrame("qrCode Generator");
gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
gui.setSize(250, 340);
gui.setLayout(new BorderLayout());
gui.setResizable(false);
File iconFile = new File(VisualQrCodeGenerator.class.getResource("icon.png").getFile());
BufferedImage iconBuffered = ImageIO.read(iconFile);
gui.setIconImage(iconBuffered);
JButton generate = new JButton("Generate qrCode");
gui.add(generate,BorderLayout.SOUTH);
tfQrText = new JTextField();
PromptSupport.setPrompt("Enter Your Text ... ", tfQrText);
gui.add(tfQrText,BorderLayout.NORTH);
qrFile = new File(VisualQrCodeGenerator.class.getResource("qrCodeImage.png").getFile());
qrBufferedImage = ImageIO.read(qrFile);
ImageIcon qrImageIcon = new ImageIcon(qrBufferedImage);
JLabel image = new JLabel();
image.setIcon(qrImageIcon);
image.setHorizontalAlignment(JLabel.CENTER);
gui.add(image,BorderLayout.CENTER);
gui.setVisible(true);
generate.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent arg0) {
if(!(tfQrText.getText().equals(""))){
//create() Method make the QRcode Image
create();
}
}
});
The Error occurs on line:
BufferedImage iconBuffered = ImageIO.read(iconFile);
When I make it .jar file, it says:
My Project structure is like this:
+src
+qrCodeGenerator
-VisualQrCodeGenerator
-icon.png
-qrCodeImage.png
The code is running properly and without any error in program and I can work with it. But when I make it .jar file, it errors me as I uploaded it image.
This is normal: you can't access a classpath resource as a File object. This is because it is embedded inside a JAR. It works inside your IDE because resources are typically stored inside a temporary folder (and not inside a JAR).
You need to access it with an InputStream using Class.getResourceAsStream and use ImageIO.read(InputStream) instead.
As such, change your code to:
qrBufferedImage = ImageIO.read(VisualQrCodeGenerator.class.getResourceAsStream("qrCodeImage.png"));
and
iconBuffered = ImageIO.read(VisualQrCodeGenerator.class.getResourceAsStream("icon.png"));

Apache Commons IO File Monitoring capture events in subfolders

I'm using the following code to capture events in a given folder. It works fine, but my question is how can I capture events in sub folders in my given folder as well?
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.monitor.FileAlterationListener;
import org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;
public class Monitor {
public Monitor() {
}
//path to a folder you are monitoring .
public static final String FOLDER = MYPATH;
public static void main(String[] args) throws Exception {
System.out.println("monitoring started");
// The monitor will perform polling on the folder every 5 seconds
final long pollingInterval = 5 * 1000;
File folder = new File(FOLDER);
if (!folder.exists()) {
// Test to see if monitored folder exists
throw new RuntimeException("Directory not found: " + FOLDER);
}
FileAlterationObserver observer = new FileAlterationObserver(folder);
FileAlterationMonitor monitor =
new FileAlterationMonitor(pollingInterval);
FileAlterationListener listener = new FileAlterationListenerAdaptor() {
// Is triggered when a file is created in the monitored folder
#Override
public void onFileCreate(File file) {
// "file" is the reference to the newly created file
System.out.println("File created: "+ file.getCanonicalPath());
}
// Is triggered when a file is deleted from the monitored folder
#Override
public void onFileDelete(File file) {
try {
// "file" is the reference to the removed file
System.out.println("File removed: "+ file.getCanonicalPath());
// "file" does not exists anymore in the location
System.out.println("File still exists in location: "+ file.exists());
} catch (IOException e) {
e.printStackTrace(System.err);
}
}
};
observer.addListener(listener);
monitor.addObserver(observer);
monitor.start();
}
}
I've read here enter link description here that this code is suppose to capture events in sub folders as well, but I does not work.
The statement you make regarding the hyperlink after your code is not accurate. The code in Capture events happening inside a directory DOES capture certain events (file create, file delete) in the main/root directory and subfolders. It does not monitor file modification or folder operations (create, delete, rename, etc.).
I have just tested it on 3 levels down (nested subfolders). As such the code you are referring to accomplishes what you are asking for. If you need something different please re-phrase/re-word your question.
If you need more information on the subject you might find this link: https://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/monitor/FileAlterationListenerAdaptor.html useful. It definitely helped me.

How to call a method from property file using Java and Selenium WebDriver?

Currently Working on Selenium WebDriver and code I'm writing in Java.
I have created a MasterScript called Master.java which is the main script and it looks like this:
package test;
import org.openqa.selenium.WebDriver;
public class MasterScript {
public static void main(String[] args) throws Exception {
//*****************************************************
// Calling Methods
//*****************************************************
LoginOneReports utilObj = new LoginOneReports ();
WebDriver driver;
driver=utilObj.setUp();
if(utilObj.Login()){
System.out.println("Login sucessfully completed");
} else {
System.out.println("Login failed");
System.exit(0);
}
NewPR utilObj1 = new NewPR(driver); // instead of calling one PR it need to pick from the property file and it need to select the KPI in UI
if(utilObj1.test()){
System.out.println("NewPR KPI page has opened");
} else {
System.out.println("NewPR KPI not able to open");
}
FilterSection utilObj2 =new FilterSection(driver);
utilObj2.FilterMatching();
}
}
Put this dynamic values in the property file where each and every time it need to go to the property file and fetch the value, based on the value the related java file need to called.
Hi Just for example we will call the property file as setup.txt
say for example you have a url in ur setup file as "internal.url=https://google.com"
create a constructor
public MasterScript() throws IO Exception
{
setup_details();
}
public void setup_details()throws IOException{
FileInputStream inStream;
inStream = new FileInputStream(new File("Setupfiles\\setup.txt"));
Properties prop = new Properties();
prop.load(inStream);
internal_url=prop.getProperty("internal.url");
}
IN THE SETUP FILE*
internal.url=https://google.com
name the txt file as setup.txt
Now while using that in the main class u can just use "driver.get(internal_url);"
Hope This helps you...

Java: opening a resource (txt file) which is in a jar with OS standard application

i get the error "AWT-EventQueue-0 java.lang.IllegalArgumentException: URI is not hierarchical".
-I'm trying to use the java.awt.Desktop api to open a text file with the OS's default application.
-The application i'm running is launched from the autorunning jar.
I understand that getting a "file from a file" is not the correct way and that it's called resource. I still can't open it and can't figure out how to do this.
open(new File((this.getClass().getResource("prova.txt")).toURI()));
Is there a way to open the resource with the standard os application from my application?
Thx :)
You'd have to extract the file from the Jar to the temp folder and open that temporary file, much like you would do with files in a Zip-file (which a Jar basically is).
You do not have to extract file to /tmp folder. You can read it directly using `getClass().getResourceAsStream()'. But note that path depend on where your txt file is and what's your class' package. If your txt file is packaged in root of jar use '"/prova.txt"'. (pay attention on leading slash).
I don't think you can open it with external applications. As far as i know, all installers extract their compressed content to a temp location and delete them afterwards.
But you can do it inside your Java code with Class.getResource(String name)
http://download.oracle.com/javase/6/docs/api/java/lang/Class.html#getResource(java.lang.String)
Wrong
open(new File((this.getClass().getResource("prova.txt")).toURI()));
Right
/**
Do you accept the License Agreement of XYZ app.?
*/
import java.awt.Dimension;
import javax.swing.*;
import java.net.URL;
import java.io.File;
import java.io.IOException;
class ShowThyself {
public static void main(String[] args) throws Exception {
// get an URL to a document..
File file = new File("ShowThyself.java");
final URL url = file.toURI().toURL();
// ..then do this
SwingUtilities.invokeLater( new Runnable() {
public void run() {
JEditorPane license = new JEditorPane();
try {
license.setPage(url);
JScrollPane licenseScroll = new JScrollPane(license);
licenseScroll.setPreferredSize(new Dimension(305,90));
int result = JOptionPane.showConfirmDialog(
null,
licenseScroll,
"EULA",
JOptionPane.OK_CANCEL_OPTION);
if (result==JOptionPane.OK_OPTION) {
System.out.println("Install!");
} else {
System.out.println("Maybe later..");
}
} catch(IOException ioe) {
JOptionPane.showMessageDialog(
null,
"Could not read license!");
}
}
});
}
}
There is JarFile and JarEntry classes from JDK. This allows to load a file from JarFile.
JarFile jarFile = new JarFile("jar_file_Name");
JarEntry entry = jarFile.getJarEntry("resource_file_Name_inside_jar");
InputStream stream = jarFile.getInputStream(entry); // this input stream can be used for specific need
If what you're passing to can accept a java.net.URLthis will work:
this.getClass().getResource("prova.txt")).toURI().toURL()

Categories

Resources