As a example:
public class Hello {
public static void main(String[] args) {
try {
OutputStream os = new FileOutputStream(new File("c.txt"));
try {
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Why was c.txt generated in the root path of current project other then the same path of the java file?
thanks.
Because the root of your project is your current working directory when starting the JVM.
You can check the user.dir system property to see what is your current working directory. If you access a file without a leading slash (Unix) or drive specifier/backslash (Windows), the files will be created relative to your current working directory.
You haven't provided a full path - this means that File constructor will use your process's current directory.
The path you provided will point to the project directory only if you want to change you can
also you can mention the full path where file is to be generated.
OutputStream os = new FileOutputStream(new File("c.txt"));
OutputStream os = new FileOutputStream(new File("D:\\c.txt"));
Related
I have class which will load the property keys. During execution it sleeps for 20 seconds, and while it is sleeping, I add a new key to the property file and save it. When the program wakes up, it again reads the property file, but its output does not show the property added during its sleep. How can I make the program recognize the property file change?
Here is my current code:
public class Test {
public static void main(String[] args) {
Properties props = new Properties();
InputStream is = Test.class.getClassLoader().getResourceAsStream(
"com/vijayspring/common/CityIns.properties");
try {
props.load(is);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(props.stringPropertyNames());
try {
Thread.sleep(20000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Properties props1 = new Properties();
InputStream is1 = Test.class.getClassLoader().getResourceAsStream(
"com/vijayspring/common/CityIns.properties");
try {
props1.load(is1);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(props1.stringPropertyNames());
}
}
As you are referring to a src folder, I assume you are using an IDE. If I knew which IDE it is exactly, I could be more accurate with my answer.
Nevertheless, the ClassLoader.getResourceAsStream() method is reading the property file from the bin (the actual name might vary per IDE) folder, which is usually built by the IDE once when it launches the java program. Any files that are no java source files, hence do not end with .java are simply copied from src to bin.
So after 20 seconds your program will read the unedited properties file in the bin folder.
This is the code
public static void readCharacters() {
try (FileInputStream fi = new FileInputStream("main/characters.dat"); ObjectInputStream os = new ObjectInputStream(fi)) {
characterList = (LinkedList<Character>) os.readObject();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
This is the structure:
And this is the Error
java.io.FileNotFoundException: main\characters.dat (The system cannot find the path specified)
What I want is to include the characters.dat file in my jar, and be able to read and write it while the program runs. Is there a different way to write the path? or to put the .dat file in a different position.
Also the writing method:
public static void writeCharacters() {
try (FileOutputStream fs = new FileOutputStream("main/characters.dat"); ObjectOutputStream os = new ObjectOutputStream(fs)) {
System.out.println("Writing Characters...");
os.writeObject(characterList);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
You can't. You can do one or the other. JAR files are not file systems, and their entries are not files. You can read it with an input stream:
InputStream in = this.getClass().getResourceAsStream("/main/characters.dat");
Check it for null before proceeding.
The jar is for read-only resources. You can use it for the initial file, as a kind of template.
Path path = Paths.get(System.getProperty("user.home") + "/myapp/chars.dat");
Files.mkdirs(path.getParentPath());
if (!Files.exists()) {
try (InputStream in =
Controller.class.getResourceAsStream("/main/characters.dat")) {
Files.copy(in, path);
}
}
The above copies the initial.dat resource from the jar to the user's home "myapp" directory, which is a common solution.
System.getProperty("user.dir") would the running directory. One can also take the jar's path:
URL url = Controller.class.getResource("/main/characters.dat");
String s = url.toExternalForm(); // "jar:file:/.... /xxx.jar!/main/characters.dat"
From that you can also construct the jar's directory. Mind to check Windows, Linux, spaces and such.
URL url = Controller.class.getProtectionDomain().getCodeSource().getLocation();
The solution above risks a NullPointerException, and works a bit differenly running inside the IDE or stand-alone.
Important note:
When using getResourceAsStream, you must start your path by slash /, this specifies the root of your jar, .getResourceAsStream("/file.txt");
In my case my file was a function argument, String filename, I had to do it like this:
InputStream in = this.getClass().getResourceAsStream("/" + filename);
Today i tested "files" instead of a normal path.
Here is my code:
File path=new File(getFilesDir(),"uf");
File test = new File(path.getAbsolutePath(),"test.txt");
if(!path.exists()){
path.mkdir();
}
if(!test.isFile()){
try {
test.createNewFile();
} catch (IOException e) {
//TODO in errorlog -> filecreation
e.printStackTrace();
}
}else{
try {
OutputStreamWriter mywriter = new OutputStreamWriter(openFileOutput(test.getAbsolutePath().toString(),Context.M ODE_PRIVATE));
mywriter.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
In the error code comes everytime: illegal Arguments: contains a path seperator!
Thank you for your help in advance
Maybe add more info about your error. But...
This error is about that you are trying to full path (include you subdirectories) to access to private data area.
Solution is use FileOutputStream, more here. And use
new File(YOUR_FILE)
to create your file.
Keep on mind that you should call method mkDirs() to create all necessary directories and subdirectories. More about mkDirs() here
Note: There is also method mkDir(), here is doc. This one will create a single directory.
I need to create a report system using LaTex templates and Java like programming language. I use JLR library but it's freeeware, this is my code:
File workingDirectory = new File("./config/output");
File desktop = new File("./config/desktop");
File invoice1 = new File("./config/templates/template1.tex");
File invoice2 = new File("./config/templates/template2.tex");
JLRGenerator pdfGen = new JLRGenerator();
pdfGen.deleteTempTexFile(false);
if (!pdfGen.generate(invoice1, desktop, workingDirectory)) {
System.out.println(pdfGen.getErrorMessage());
}
JLROpener.open(pdfGen.getPDF());
if (!pdfGen.generate(invoice2, desktop, workingDirectory)) {
System.out.println(pdfGen.getErrorMessage());
}
JLROpener.open(pdfGen.getPDF());
Searching into the Web I find JLatexMath but, as far as I know, only generates equations in LaTex and not the entire PDF. Do you know a library in Java which generates an entire PDF file using a LaTex template?
Update: I execute de .tex file using Runtime.getRuntime().exec("pdflatex.exe...") command. But I don't achive save the PDF file.
Thanks in advance
I think I have the solution, here is the code:
public void generateReport()
{
Process p;
try {
p = Runtime.getRuntime().exec("C:\\pdflatex.exe -synctex=1 -interaction=nonstopmode ./config/log/document.tex");
p.waitFor();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
It generates a .PDF and .dvi file in the same place of your .tex file. Thank you much for your help :)
I have the problem, that I create a new file in a Java program, but I always get an exception, that the new created file is not local, when I try to open it on the eclipse project explorer view.
The code where I create it is as follows:
IWorkspaceRoot workspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
IProject project = workspaceRoot.getProject(projectName);
FileUtil myFile = new FileUtil();
if (!project.getFile(FILE_NAME).exists()) {
IFile newFile = project.getFile("conf.txt");
FileInputStream fileStream = null;
try {
String temp = project + "/conf.txt";
temp = temp.substring(2);
fileStream = new FileInputStream(temp);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
newFile.create(fileStream, false, null);
} catch (CoreException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// create closes the file stream, so no worries.
try {
myFile.writeTextFile(FILE_NAME, "Seconds", output);
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
FileUtil is a class which only implements the methods write and read for the file.
The Exception I get when I try to open it begins with:
org.eclipse.core.internal.resources.ResourceException: Resource '/ProjectE1/conf.txt' is not local.
at org.eclipse.core.internal.resources.Resource.checkLocal(Resource.java:353)
at org.eclipse.core.internal.resources.File.getContentDescription(File.java:264)
at org.eclipse.core.internal.propertytester.FilePropertyTester.testContentType(FilePropertyTester.java:108)
I somehow have to get a relative path during the runtime. Because I am opening a new instance of eclipse in the program, where I can see the Project in the Project Explorer but can't open the conf.txt file because it is not local.
It looks like your resource is an absolute path to /ProjectE1/conf.txt, I'm confused why you are not using java.io.
This will help you understand relative paths, I think this may be where you are wanting to put your conf file.
File file = new File("conf.txt");
if(!file.createNewFile()){
//err
}
System.out.println(file.getAbsolutePath());
I had similar issue. This is how I fixed.
First created file in local file system (using java.io)
Did project refresh
Reload the file
File file = new File(project.getWorkspace().getRoot().getLocation() + project.getFullPath().toString() + "/relative_path_of_my_file");
file.createNewFile();
project.refreshLocal(IProject.DEPTH_INFINITE, null);
keywordFile = project.getFile("/relative_path_of_my_file");