I am trying to create a file using
File newFile = new File("myFile");
However no file called "myFile" is created. This is within a Web application Project i.e. proper form to be pakaged as a WAR but I am calling it as part of a main method (just to see how this works).
How can I make it so that a new file is created at a location relative to the current one i.e not have to put in an absolute path.
EDIT:
newFile.createFile();
Doesn't seem to work:
Here is the entire code:
import java.io.File;
import java.io.IOException;
public class Tester {
public static void main(String[] args) throws IOException{
Tester test = new Tester();
test.makeFile();
}
public void makeFile() throws IOException{
File newFile = new File("myFile");
newFile.createNewFile();
}
}
In answer to your comment. The file will be created in the current directory of the process, unless you specifiy otherwise.
// new file in current directory
File f = new File("yourFile");
f.createNewFile();
System.out.println("Path:" + f.getAbsolutePath());
To create it in a directory of your choosing:
File f = new File("c:\\yourDirectory","yourFile");
f.createNewFile();
System.out.println("Path:" + f.getAbsolutePath());
newFile.createNewFile();
you could use newFile.createNewFile();
Related
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
I have a specified URL that i cant change i.e.
/opt/local/java/config/npvr.properties
where should i place my file so that the following code can work:
String PROPERTIESFILEPATH1 = "/opt/local/java/config/npvr.properties";
File tmPropertiesFile = new File(PROPERTIESFILEPATH);
Properties properties = new Properties();
if (tmPropertiesFile.exists()) {
.....
}
i have tried placing my file in directory shown below but it didn't work:
My problem is that I can change only the location of property-file without changing the code to solve this problem. Please Help.
The file needs to go in /opt/local/java/config, not [projectdir]/opt/local/java/config. You are putting it in the wrong place
If you are using linux then add this file /opt/local/java/config/ directory location outside of your project.
"OR"
in windows C:\opt\local\java\config\ here.
use getClass().getResourceAsStream to load property file from relative of class
public class Main {
public static void main(String args[]) throws Exception{
String PROPERTIESFILEPATH = "/opt/local/java/config/npvr.properties";
//File tmPropertiesFile = new File(PROPERTIESFILEPATH);
Properties properties = new Properties();
InputStream ins=null;
//ins=new FileInputStream(PROPERTIESFILEPATH);
ins=new Main().getClass().getResourceAsStream(PROPERTIESFILEPATH);
properties.load(ins);
System.out.println(properties.get("Hello"));
}
}
Consider the code sample below. Migrator class takes two input files, processes it and writes the output to final.tbl.
I want final.tbl to be created on the same path where the folder of input files is present.
Also the execute method should take relative path of this generated final.tbl file.
public class Migrator{
public void Migrate(String path1,String path2){
PrintStream out = new PrintStream("final.tbl");//I need relative path as that of input folder path i.e path1,path2
//.....
//.....Processing
}
}
class MainProcess{
public execute(String path){
//here the execute method should the the relative path of above final.tbl file
}
public static void main(String args[]){
}
}
Path path = Paths.get(path1);
PrintStream out = new PrintStream(path.getParent().toString() + "\\final.tbl");
I think you can use getAbsolutePath to get path to your input files:
public class Migrator{
public void Migrate(String path1,String path2){
File f = new File(path1);
String absolutePath = f.getAbsolutePath(); // use absolutePath for your PrintStream
PrintStream out = new PrintStream(absolutePath);//I need relative path as that of input folder path i.e path1,path2
//.....
//.....Processing
}
}
Hope it helped
Use the getParentFile()
File target = new File(new File(path1).getParentFile(), "final.tbl");
PrintStream out = new PrintStream(target);
I'm trying to get a resource (image.png, in the same package as this code) from a static method using this code:
import java.net.*;
public class StaticResource {
public static void main(String[] args) {
URL u = StaticResource.class.getClass().getResource("image.png");
System.out.println(u);
}
}
The output is just 'null'
I've also tried StaticResource.class.getClass().getClassLoader().getResource("image.png");
, it throws a NullPointerException
I've seen other solutions where this works, what am I doing wrong?
Remove the ".getClass()" part.
Just use
URL u = StaticResource.class.getResource("image.png");
Always try to place the resources outside the JAVA code to make it more manageable and reusable by other package's class.
You can try any one
// Read from same package
URL url = StaticResource.class.getResource("c.png");
// Read from same package
InputStream in = StaticResource.class.getResourceAsStream("c.png");
// Read from absolute path
File file = new File("E:/SOFTWARE/TrainPIS/res/drawable/c.png");
// Read from images folder parallel to src in your project
File file = new File("images/c.jpg");
// Read from src/images folder
URL url = StaticResource.class.getResource("/images/c.png")
// Read from src/images folder
InputStream in = StaticResource.class.getResourceAsStream("/images/c.png")
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()