This is my code snippet:
static String filepath = "test.txt";
public static void main(String[] args) throws IOException {
try{
BufferedReader reader = new BufferedReader(new FileReader(filepath));
String l = reader.readLine();
System.out.println(l);
}catch (FileNotFoundException e){
System.out.println(e);
}
catch(IOException e){
System.out.println(e);
}
java.io.FileNotFoundException: test.txt (No such file or directory)
This is the exception I am getting.
What file path should I use? I put the text file in the bin folder.
I am running Eclipse on Ubuntu, it that matters.
If you are running eclipse and have a java project, then just put the file in the project and it will work.
Place the file at the root directory of the project folder. If your project root directory is FileReader, then place the file into it
Related
This sample is supposed to locate the copied over .zip file from the build output directory but for some reason it doesn't find that file. I created a resource directory in the root directory and marked it as "Resource Root" and still didn't work. Any help is appreciated. Here is a snippet of the code:
if (install && package == null) {
File file = new File("file.zip");
byte[] bytes = new byte[(int) file.length()];
try {
FileInputStream inputStream = new FileInputStream(file);
inputStream.read(bytes);
inputStream.close();
}
catch (FileNotFoundException ex) {
System.out.println("File Not Found.");
return;
}
catch (IOException ex) {
System.out.println("Error Reading The File.");
ex.printStackTrace();
}
Here is a screenshot of the project structure:
Project Structure
I suppose you mean you've created the file in the /main/resources folder of your project?
If that's so, then you can copy it as such:
public static void main(String[] args) throws IOException {
var path = Main.class.getResourceAsStream("/myfile.txt");
Files.copy(path, Path.of("file.txt"));
}
I am using the following code to open a pdf file from java. The code works when I run the application from the IDE. However, when generating the jar and executing it, the code stops working. I do not know what I'm doing wrong. I have tried changing the jar of folders but it still does not work. It seems that the problem is how ubuntu 16.04 handles the routes because in windows this works correctly. The application does not throw exceptions
The way I get the pdf I do the same for another application but in it I get an image and it works both in the jar and in executing it in the ide.
jbTree.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/tree.png")));
Button code
if (Desktop.isDesktopSupported()) {
try {
File myFile = new File (getClass().getResource("/help/help.pdf").toURI());
Desktop.getDesktop().open(myFile);
} catch (IOException | URISyntaxException ex) {
Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
}
}
The solution is run the application through the console. Trying to run it in another way does not work.
When you run the project from your IDE then the root of your project is the System.getProperty("user.dir") e.g if it Your project root folder is PDFJar the it will look for the help.pdf in the PDFJar/src/project/help/ folder.
After building your project to jar file the executable jar is build and executed from a dist or bin folder which is now the System.getProperty("user.dir") and the help.pdf will be seeked in the dist/src/project/help/ folder.
You either create the folder /src/project/help/ with help.pdf in it in your dist or bin directory or put your Jar file in your project root
EDITED
You can't access a resources file packed into your JAR archive as file except as input stream, The reason it works from you IDE is because the file exist in the src folder as the executed directory is your project folder. You will need to create the file outside the JAR achive then read the stream into it so you can call Desktop to open it.
package stackoverflow;
import java.awt.Desktop;
import java.awt.HeadlessException;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
/**
*
* #author thecarisma
*/
public class StackOverflow {
public void openHelpFile() {
OutputStream outputStream = null;
try {
File outFile = new File("./help.pdf");
outFile.createNewFile(); //create the file with zero byte in same folder as your jar file or a folder that exists
InputStream in = getClass().getResourceAsStream("/help/help.pdf");
outputStream = new FileOutputStream(outFile);
int read = 0;
//now we write the stream into our created help file
byte[] bytes = new byte[1024];
while ((read = in.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
if (outFile.exists()) {
String path= outFile.getAbsolutePath();
JOptionPane.showMessageDialog(null, path);
if (Desktop.isDesktopSupported()) {
JOptionPane.showMessageDialog(null, "Enter");
try {
File myFile = new File (path);
Desktop.getDesktop().open(myFile);
} catch (IOException ex) {
JOptionPane.showMessageDialog(null, "Exception");
}
}
} else {
JOptionPane.showMessageDialog(null, "Error Occur while reading file");
}
} catch (HeadlessException | IOException ex) {
Logger.getLogger(StackOverflow.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
outputStream.close();
} catch (IOException ex) {
Logger.getLogger(StackOverflow.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
StackOverflow stackOverFlow = new StackOverflow();
stackOverFlow.openHelpFile();
//the bellow example works for file outside the JAR archive
/**
String path= new File("help.pdf").getAbsolutePath();
JOptionPane.showMessageDialog(null, path);
if (Desktop.isDesktopSupported()) {
JOptionPane.showMessageDialog(null, "Enter");
try {
File myFile = new File (path);
Desktop.getDesktop().open(myFile);
} catch (IOException ex) {
JOptionPane.showMessageDialog(null, "Exception");
}
} **/
}
}
DETAIL
When your resources file is packed into the JAR archive it cannot be accessed as a file except as a stream of file. The location of the file will be absolute in the JAR archive such as the /help/help.file.
If you just want read the content of the resources such as conf, xml, text file or such you can just read it into BufferReader i.e
InputStream in = getClass().getResourceAsStream("/conf/conf.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
else if it a binary file you will need to create a file outside the jar file with 0 byte then read the resources stream from the JAR archive into the created file.
NOTE: You should check if the help file already exist with the same size before reading from the JAR archive to prevent reading multiple time and skip the process to increase you run time. Take note while creating your file as creating a file in a folder that does not exist in JAVA is not possible.
YOU CAN OPEN YOUR .jar FILE WITH AN ARCHIVE MANAGER, TO VIEW IT STRUCTURE
Here is My WriteFile
WriteFile.writeFile(str, "./test/my.html");
And writeFile() method code
public static void writeFile(String content, String fileName)
{
try
{
File file = new File(fileName);
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
This Code Working fine With Windows but in Linux I am getting below exception
java.io.IOException: No such file or directory
at java.io.UnixFileSystem.createFileExclusively(Native Method)
at java.io.File.createNewFile(File.java:1006)
at org.sewa.util.WriteFile.writeFile(WriteFile.java:25)
Behavior of createNewFile is the same in Windows and Linux, so most likely the path of the file you're specifing exists in Windows while it does not in Linux. In your example, test/ directory does not exist in Linux in the directory where you're executing the program. If you want to create the whole path, see File#mkdirs.
If I want to create a file in C:/a/b/test.txt, can I do something like:
File f = new File("C:/a/b/test.txt");
Also, I want to use FileOutputStream to create the file. So how would I do it? For some reason the file doesn't get created in the right directory.
The best way to do it is:
String path = "C:" + File.separator + "hello" + File.separator + "hi.txt";
// Use relative path for Unix systems
File f = new File(path);
f.getParentFile().mkdirs();
f.createNewFile();
You need to ensure that the parent directories exist before writing. You can do this by File#mkdirs().
File f = new File("C:/a/b/test.txt");
f.getParentFile().mkdirs();
// ...
With Java 7, you can use Path, Paths, and Files:
import java.io.IOException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class CreateFile {
public static void main(String[] args) throws IOException {
Path path = Paths.get("/tmp/foo/bar.txt");
Files.createDirectories(path.getParent());
try {
Files.createFile(path);
} catch (FileAlreadyExistsException e) {
System.err.println("already exists: " + e.getMessage());
}
}
}
Use:
File f = new File("C:\\a\\b\\test.txt");
f.mkdirs();
f.createNewFile();
Notice I changed the forward slashes to double back slashes for paths in Windows File System. This will create an empty file on the given path.
String path = "C:"+File.separator+"hello";
String fname= path+File.separator+"abc.txt";
File f = new File(path);
File f1 = new File(fname);
f.mkdirs() ;
try {
f1.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
This should create a new file inside a directory
A better and simpler way to do that :
File f = new File("C:/a/b/test.txt");
if(!f.exists()){
f.createNewFile();
}
Source
Surprisingly, many of the answers don't give complete working code. Here it is:
public static void createFile(String fullPath) throws IOException {
File file = new File(fullPath);
file.getParentFile().mkdirs();
file.createNewFile();
}
public static void main(String [] args) throws Exception {
String path = "C:/donkey/bray.txt";
createFile(path);
}
Create New File in Specified Path
import java.io.File;
import java.io.IOException;
public class CreateNewFile {
public static void main(String[] args) {
try {
File file = new File("d:/sampleFile.txt");
if(file.createNewFile())
System.out.println("File creation successfull");
else
System.out.println("Error while creating File, file already exists in specified path");
}
catch(IOException io) {
io.printStackTrace();
}
}
}
Program Output:
File creation successfull
To create a file and write some string there:
BufferedWriter bufferedWriter = Files.newBufferedWriter(Paths.get("Path to your file"));
bufferedWriter.write("Some string"); // to write some data
// bufferedWriter.write(""); // for empty file
bufferedWriter.close();
This works for Mac and PC.
For using the FileOutputStream try this :
public class Main01{
public static void main(String[] args) throws FileNotFoundException{
FileOutputStream f = new FileOutputStream("file.txt");
PrintStream p = new PrintStream(f);
p.println("George.........");
p.println("Alain..........");
p.println("Gerard.........");
p.close();
f.close();
}
}
When you write to the file via file output stream, the file will be created automatically. but make sure all necessary directories ( folders) are created.
String absolutePath = ...
try{
File file = new File(absolutePath);
file.mkdirs() ;
//all parent folders are created
//now the file will be created when you start writing to it via FileOutputStream.
}catch (Exception e){
System.out.println("Error : "+ e.getmessage());
}
I have a config.properties file at the root of my blackberry project (same place as Blackberry_App_Descriptor.xml file), and I try to access the file to read and write into it.
See below my class:
public class Configuration {
private String file;
private String fileName;
public Configuration(String pathToFile) {
this.fileName = pathToFile;
try {
// Try to load the file and read it
System.out.println("---------- Start to read the file");
file = readFile(fileName);
System.out.println("---------- Property file:");
System.out.println(file);
} catch (Exception e) {
System.out.println("---------- Error reading file");
System.out.println(e.getMessage());
}
}
/**
* Read a file and return it in a String
* #param fName
* #return
*/
private String readFile(String fName) {
String properties = null;
try {
System.out.println("---------- Opening the file");
//to actually retrieve the resource prefix the name of the file with a "/"
InputStream is = this.getClass().getResourceAsStream(fName);
//we now have an input stream. Create a reader and read out
//each character in the stream.
System.out.println("---------- Input stream");
InputStreamReader isr = new InputStreamReader(is);
char c;
System.out.println("---------- Append string now");
while ((c = (char)isr.read()) != -1) {
properties += c;
}
} catch (Exception e) {
}
return properties;
}
}
I call my class constructor like this:
Configuration config = new Configuration("/config.properties");
So in my class, "file" should have all the content of the config.properties file, and the fileName should have this value "/config.properties".
But the "name" is null because the file cannot be found...
I know this is the path of the file which should be different, but I don't know what i can change... The class is in the package com.mycompany.blackberry.utils
Thank you!
I think you need to put the config.properties file into a source folder when you build the project, you can create a "resources" folder as a src folder and put the config file in it, than you can get the file in the app
Try putting the file in the same package as the class?
Class clazz = Class.forName("Configuration");
InputStream is = addFile.getResourceAsStream(fName);