I am using Java to create a file with some data in it. But I encouter a problem. Indeed I succeed in creating a file and write "hello" in it when I run from Eclipse. But when I export that code in a jar file and I tried to execute it in the command line (java -jar myappli.jar), the file is not created. I don't understand why.
Here is my java file which is quite simply.
If you have any answers I would be happy to have it :)
Thank you.
package testjar;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
public class Main {
public static void main(String[] args)
{
FileOutputStream f = null;
try
{
f = new FileOutputStream(new File("Export_XML.xml"));
System.setOut(new PrintStream(f));
System.out.println("hello");
}
catch(java.io.IOException e)
{
e.printStackTrace();
}
finally
{
try
{
if(f!=null)
f.close();
}
catch(IOException e) {e.printStackTrace();}
}
}
}
If you're not getting exceptions, it is most likely being created. The difference is the working directory. Since you're not specifying an absolute path when calling new File the JVM will create the file in the current working directory for the JVM. This is likely different when you're running from the jar vs where it is when you run from Eclipse.
I cannot see what is specifically wrong, but try making the new File('Export_XML.xml') into its own variable, then doing xmlFile.createNewFile(); Also, I discourage the use of System.setOut() as your program isn't the only part of Java to use it.
Related
I am learning basic I/O for java, and the following example is from Oracle's tutorial. The program flows a FileNotFound exception. I place the file under the working directory, and I also tried to use absolute file path, and the result is still the same. I use Eclipse to write the code. What could be causing this exception? Thanks
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class CopyBytes {
public static void main(String[] args) throws IOException {
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("xanadu.txt");
out = new FileOutputStream("outagain.txt");
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
} finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
There are a lot of things that can cause that exception. Here are a few things to try:
-Verify that Xanadu.txt is a file using the isFile() method. If it returns false then you know where your problem is.
-Try placing the file in the project directory.
-Given that you already tried using the absolute file path I would also make sure that your program has permission to look at and write to the file. To check if eclipse has permission go to the properties of your file
Place the file xanadu.txt in the project directory and FileNotFoundException will go away.
FileInputStream will expect an existing input file.
The code probably isn't being executed from the path you expected.
You should use the home folder for this. C:\Users\<User Name> on windows and /home/<User Name> on linux. You can create a folder there to put your files.
To get the home directory, you can use this.
System.getProperty("user.dir")
Other solution would be to pack the files inside the JAR.
If you want to debug your problem, you can get the current directory like this.
<Your Class>.class.getProtectionDomain().getCodeSource().getLocation()
I have had two years experience in Java but have not touched in a year therefore a little rusty.
I am trying to reading a text file line by line using Java8 (the new way).
Based on a forum I have read I am using the following code:
package codeTest;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Stream;
public class Main {
public static void main(String[] args) {
String filename = "RouterInfo.txt";
try(Stream<String> stream = Files.lines(Paths.get(filename))) {
stream.forEach(System.out::println);
} catch(IOException e) {
e.printStackTrace();
}
}
}
But no matter what I try I keep getting a java.nio.file.NoSuchFileException.
Here is a picture of my file directory in eclipse:
Can anybody help?
Your text file is in src/codeTest folder so it should be
"src/codeTest/RouterInfo.txt"
Your Java code is correct. Only your RouterInfo.txt is in the wrong place. Just put it into your project directory instead of into src.
Replace filename string with "./src/RounterInfo.txt".
The text file should not be put in the src folder but in the folder that contains src.
Therefore the new folder path should be:
Answer/sample.txt
Answer would be the name of the folder containing src.
As the title says, I have a PDF document which is stored locally and using Java I would like to open it on an arbitrary page. My question is much the same as this question, however the proposed solution seems rather hacky so I would prefer a more conventional answer if possible. I understand that the code shown below will not work because #page=5 should be appended to the URL in the browser and not the file path, however I'm really not sure what to try next. Any help would be much appreciated!
import java.io.File;
import java.io.IOException;
import java.net.URL;
public class OpenPdfTest {
public OpenPdfTest(){
try {
File myFile = new File("test.pdf");
URL url = myFile.toURI().toURL();
Process p = Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url + "#page=5");
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args){
new OpenPdfTest();
}
}
What about using http://tika.apache.org/ and read the whole file, convert it and use the part of the pdf File that you want. You can read in any File you want with Apache Tika. With this Lib you can open any kind of files, also pdf-Files and proceed them.
Take my Answer just as a first guess.
Trying to learn how to read text files in Java. I have placed the text file within the same folder as IdealWeight.java. Am I missing something here?
IdealWeight.java
package idealweight;
import java.util.*;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class IdealWeight
{
public static void main(String[] args)
{
Scanner fileIn = null; //Initializes fileIn to empty
try
{
fileIn = new Scanner
(
new FileInputStream
("Weights.txt")
);
}
catch (FileNotFoundException e)
{
System.out.println("File not found!");
}
}
}
You could also put the file in the classpath and then do this:
InputStream in = this.getClass().getClassLoader()
.getResourceAsStream("Weights.txt");
Just another idea.
The java file IO system does not look for the file in the same directory as the class, but in the "default" directory for the application. Any application you run has a directory that it regards as its default, and that's where it would attempt to open this file. Try putting a full pathname to the file.
Or put the file you want to read in a directory, and run the application from that directory (in a terminal window) with "java IdealWeight".
You need to put Weights.txt in your working directory, not in the directory with the source file. If you're using Eclipse or a similar IDE, the this is probably the project root. As per this answer, you can use this snippet to get the full path to your working directory:
System.out.println("Working Directory = " + System.getProperty("user.dir"));
Check the result of running that command, and that should tell you where to put your text file. Once you have the text file in the right place then the code you posted should work fine.
I'm trying to get my submit button to save the GUI in a text file, I've made the GUI and the button listener ...etc but I'm having trouble making the method that saves the information from the GUI into a text file.
so far i have:
public void save() {
File k1 = new File("documents/"+"newfile.txt");
try {
k1.createNewFile();
FileWriter kwriter = new FileWriter(k1);
BufferedWriter bwriter = new BufferedWriter(kwriter);
bwriter.write(txtField1.getText().trim());
bwriter.newLine();
bwriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
but it doesn't seem to work, nothing happens; is there anything I'm missing?
You're file is called .txt - perhaps insert a name in the first row:
File k1 = new File("documents/filename.txt");
You should be getting an error when running that code.
The problem is that the document directory doesn't exist or it is not where you expected.
You can check for the parent directory with:
if(!k1.getParentFile().exists()){
k1.getParentFile().mkdirs();
}
Alternatively you need to set the file to be a more precise location.
org.apache.commons.lang.SystemUtils might be able to help you out here with user home.
i was just think is there a easier way, for example i already have the Jfilechoser open a "save as box" when the "submit" button is pressed so is there a easier way to create the file (saving the gui infomation in a txt file) ?
This is a continuation on your previous question. You should just get the selected file and write to it with help of any Writer, like PrintWriter.
File file = fileChooser.getSelectedFile();
PrintWriter writer = new PrintWriter(file);
try {
writer.println(txtField1.getText().trim());
writer.flush();
} finally {
writer.close();
}
Don't overcomplicate by creating a new File() on a different location and calling File#createFile(). Just writing to it is sufficient.
See also:
Java IO tutorial
update here's an SSCCE, you can just copy'n'paste'n'compile'n'run it.
package com.example;
import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import javax.swing.JFileChooser;
public class Test {
public static void main(String[] args) throws IOException {
JFileChooser fileChooser = new JFileChooser();
if (fileChooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
PrintWriter writer = new PrintWriter(file);
try {
writer.println("Hello");
writer.flush();
} finally {
writer.close();
}
Desktop.getDesktop().open(file);
}
}
}
My guess is that the file is being created, but not in the directory that you expect. Check the value of the user.dir system property and see what it shows. This is the current working directory of your JVM.
You may need to either:
Specify a full path in the code (as Martin suggested), e.g. new File("/home/foo/newfile.txt")
Change the working directory of the JVM. The way that you do this depends on how you are launching it (e.g. if you are running the java command directly from a CLI, then just switch directories first, if you are running from an IDE then change the launch configuration, etc.).
As far as I know, you cannot change the working directory at runtime (see this SO question).
Your code is working for me with minor change.
As a debugging process, I would completely delete the directory path and try to use a file only..
instead of
File k1 = new File("documents/"+"newfile.txt");
use
File k1 = new File("newfile.txt");
Check where your file is generated and then create directory there..
Good luck!!