I tried to open from the normal eclipse it worked fine, but when exported same file to a jar
its giving an error.
Can anyone help?
public void mouseClicked(MouseEvent e) {
Process process;
try {
String resourceLocation = MainPanel.class.getProtectionDomain().getCodeSource().getLocation().getPath();
resourceLocation += "/com/microsoftplatformready/resources/images/endUserLicenseAgreement.docx";
process = Runtime.getRuntime().exec("soffice -reader "+resourceLocation);
process.waitFor();
process.destroy();
} catch (Exception e1) {
e1.printStackTrace();
}
}
Please help
Thanks
As Joop Eggen already said in the comment, first create a new temp file and copy your actual document to the temp file and open this one instead.
The reason is simply, Openoffice can't read files stored in an archive.
Path temp = Files.createTempFile("prefix", "suffix.ext");
Files.copy(getClass().getResourceAsStream(resourceLocation), temp);
process = Runtime.getRuntime().exec("soffice -reader "+ temp.toAbsolutePath().toString())
Related
i have the current code:
public void crearArchivo(String nombre) {
archivo = new File(nombre.replaceAll("\\s", "") + ".txt");
if (!archivo.exists()) {
try {
archivo.createNewFile();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void crearCarpeta(String nombreCarpeta){
File directorio = new File(nombreCarpeta);
directorio.mkdir();
}
public void crearArchivoDatos(String nombreArchivo, ArrayList<String>datos) {
crearArchivo(nombreArchivo);
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(archivo));
for (int i = 0; i < datos.size(); i++) {
bw.write(datos.get(i));
}
bw.close();
} catch (Exception e) {
//e.printStackTrace();
}
}
the first method create a file only if it doesnt exist and the second one create a folder finally the third method save the data my problem is that i want to save some files on the folder i created first how can i set a path to save those file there, also i have the problem that this little program will execute at diferent computers so the path will change for any computer
You can get paths of folders on any computer using System.getProperty(...) - for example System.getProperty("user.home") gives you the current user directory (from which you can get to the desktop and other folders), and System.getProperty("user.dir") gives you the path of the folder from which your program is executed.
Creating or modifying files in Java can be done with the Java 8 NIO.2 methods.
Here is a link to the Oracle documentation : https://docs.oracle.com/javase/tutorial/essential/io/fileio.html
For your question, you have to declare a relative path, so it will be independent of the computer it will be executed on, rather than an absolute path, which begin on the root of the filesystem.
I have been experimenting with writing to text files for output instead of System.out.println(). When I try this, though, nothing seems to be written. What is the issue with my code?
try{
List<String> lines = Arrays.asList("Data Goes Here");
Path file = Paths.get("output.txt");
Files.write(file, lines, Charset.forName("UTF-8"));
}
catch (IOException ex) {
System.out.println("Frick, something broke. Sorry folks, go home.");
}
I just did a small change to your code by passing the path as the resources directory located in the root of my project. I was able to write to the file successfully.
Here is the updated code:
try {
List<String> lines = Arrays.asList("Data Goes Here");
Path file = Paths.get("./resources/test.txt");
Files.write(file, lines, Charset.forName("UTF-8"));
}
catch (IOException ex) {
ex.printStackTrace();
System.out.println("Frick, something broke. Sorry folks, go home.");
}
This is my file directory
I am trying to open admin.dat for reading but dont understand why am i unable to open the file and the FileNotFound exception is always thrown
Code:
public void readfile(){
try{
Scanner filereader = new Scanner(new File("admin.dat"));
String data;
while(filereader.hasNextLine()){
data = filereader.nextLine();
System.out.println(data);
}
}
catch (FileNotFoundException e){
System.out.println("File not found");
}
catch (IOException e){
System.out.println("Error while reading file");
}
}
Generally when you launch app through IDE they set current directory to the root of the project so you need to pass relative path from there
You can check what is set as current directory by
System.out.println(System.getProperty("user.dir"));
ALso it will just work as long as the file exists as a real File, if you bundle it in jar or some other form of archive it will stop working, so better to read it as Resource from classpath
This is the code I use when I try to read some specific text in a *.txt file:
public void readFromFile(String filename, JTable table) {
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new FileReader(filename));
String a,b,c,d;
for(int i=0; i<3; i++)
{
a = bufferedReader.readLine();
b = bufferedReader.readLine();
c = bufferedReader.readLine();
d = bufferedReader.readLine();
table.setValueAt(a, i, 0);
table.setValueAt(b, i, 1);
table.setValueAt(c, i, 2);
table.setValueAt(d, i, 3);
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
//Close the reader
try {
if (bufferedReader != null) {
bufferedReader.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
And it is called in this way:
readFromFile("C:/data/datafile.txt", table1)
The problem is the following: the 1st time I open the program the *.txt file I'm going to read does not exist, so I thought I could use the function exists(). I have no idea about what to do, but I tried this:
if(("C:/data/datafile.txt").exists()) {
readFromFile("C:/data/datafile.txt", table1)
}
It is not working because NetBeans gives me a lot of errors. How could I fix this?
String has no method named exists() (and even if it did it would not do what you require), which will be the cause of the errors reported by the IDE.
Create an instance of File and invoke exists() on the File instance:
if (new File("C:/data/datafile.txt").exists())
{
}
Note: This answer use classes that aren't available on a version less than Java 7.
The method exists() for the object String doesn't exist. See the String documentation for more information. If you want to check if a file exist base on a path you should use Path with Files to verify the existence of the file.
Path file = Paths.get("C:/data/datafile.txt");
if(Files.exists(file)){
//your code here
}
Some tutorial about the Path class : Oracle tutorial
And a blog post about How to manipulate files in Java 7
Suggestion for your code:
I'll point to you the tutorial about try-with-resources as it could be useful to you. I also want to bring your attention on Files#readAllLines as it could help you reduce the code for the reading operation. Based on this method you could use a for-each loop to add all the lines of the file on your JTable.
you can use this code to check if the file exist
Using java.io.File
File f = new File(filePathString);
if(f.exists()) { /* do something */ }
You need to give it an actual File object. You're on the right track, but NetBeans (and java, for that matter) has no idea what '("C:/data/datafile.txt")' is.
What you probably wanted to do there was create a java.io.File object using that string as the argument, like so:
File file = new File ("C:/data/datafile.txt");
if (file.exists()) {
readFromFile("C:/data/datafile.txt", table1);
}
Also, you were missing a semicolon at the end of the readFromFile call. Im not sure if that is just a typo, but you'll want to check on that as well.
If you know you're only ever using this File object just to check existence, you could also do:
if (new File("C:/data/datafile.txt").exists()) {
readFromFile("C:/data/datafile.txt", table1);
}
If you want to ensure that you can read from the file, it might even be appropriate to use:
if(new File("C:/data/datafile.txt").canRead()){
...
}
as a condition, in order to verify that the file exists and you have sufficient permissions to read from the file.
Link to canRead() javadoc
I'm trying to read a file in eclipse and print it. The problem is that the compiler always says to me that the file or directory doesn't exist. I have to use relative paths.
The relevant part of the project routes is:
uva.pfc.refactoringEngine.core <--Project
...
src
uva.pfc.refactoringengine.core.actions <-- Actual Package
...
CreateEnumSetPlusClas.java <--File from I want to read the EnumSetPlus.java file
...
EnumSetPlus.java <-- File I want read and print
This is the code:
String total="";
File actual = new File("src/EnumSetPlus.java");
FileReader filereader = null;
try {
filereader = new FileReader(actual);
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block e.printStackTrace();
}
BufferedReader input = new BufferedReader(filereader);
try {
while ((line = input.readLine()) != null)
{
total += line + "\n";
}
input.close();
}
catch (IOException e) {
// TODO Auto-generated catch block e.printStackTrace();
}
System.out.println(total);
I think the problem is that I have to do something if I want the file path recognised by de eclipse project.
Could you help me??
Thaks beforehand.
I'd use getClass().getResourceAsStream("/EnumSetPlus.txt") - this will look for the file on the root of the classpath (which is bin/, but all files from src go to bin). You then get an InputStream which you can adapt to Redaer via new InputStreamReader(stream, encoding)
In Eclipse the current working directory is src by default.
Try this
File actual = new File("EnumSetPlus.txt");
Also I would look into Kevin's answer too. :-)
Try:
String filePath = "/EnumSetPlus.java";
File actual = new File(ClassLoader.getSystemResource(filePath).getFile());
Your example says that you want to read a file called EnumSetPlus.java but the source code is looking for a file called EnumSetPlus.txt.