FileNotFoundException while reading a xlsx file - java

I'm trying to read a .xlsx file from the project folder using the following code, but it always throws FileNotFoundException. I have attached the project structure where the file is.
public static void main(String[] args) {
try {
String excelFilePath = "‪DataModel.xlsx";
File file = new File(excelFilePath);
FileInputStream fis = new FileInputStream(file);
} catch (Exception ex) {
System.out.print(ex);
}
}

This is how I normally would approach it:
File file = new File( javaApplication2.class.getResource( excelFilePath ).getPath() );

classLoader.getResource() solved the problem

Related

Unable to write to the file, Created in java using File class

Class MakeDirectory contains the constructor, and in the constructor I created a directory and inside that directory I created a file. But I am unable to write anything to the newly created file, even though the file and directory have been generated successfully. Can anyone help me figure out why I am not able to write to the file Anything.txt?
public class MakeDirectory {
MakeDirectory() throws IOException{
// Creates Directory
File mydir= new File("MyDir");
mydir.mkdir();
// Creates new file object
File myfile = new File("MyDir","Anyfile.txt");
//Create actual file Anyfile.txt inside the directory
PrintWriter pr= new PrintWriter(myfile);
pr.write("This file is created through java");
}
public static void main(String args[]) throws IOException {
new MakeDirectory();
}
}
If you want to use PrintWriter you need to know that it is not automatically flushing. After you write you need to flush. Also, don't forget to close your PrintWriter!
PrintWriter pw = new PrintWriter(myFile);
pw.write("text");
pw.flush();
pw.close();
An approach available in Java 7 employs the try-with-resources construct. Using this feature, the code would look like the following:
try (PrintWriter pw = new PrintWriter("myFile")) {
pw.write("text");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
With BufferedWriter you can just write the strings, arrays or characters data directly to the file:
void makeDirectory() throws IOException {
// Creates Directory
File mydir = new File("MyDir");
mydir.mkdir();
// Creates new file object
File myfile = new File("MyDir", "Anyfile.txt");
//Create actual file Anyfile.txt inside the directory
BufferedWriter bw = new BufferedWriter(new FileWriter(myfile.getAbsoluteFile()));
String str = "This file is created through java";
bw.write(str);
bw.close();
}

How to get file from resource folder as File?

I want to get a file from resources folder if it exists and create it there if it doesn't. I want to access it as file. class.getResource() doesn't work as it returns an URL. class.getResourceAsStream() gives input stream, but then I can't write in it or can I somehow?
import java.io.File;
import java.io.FileNotFoundException;
public class Statistika {
File file;
public Statistika() {
try {
file = Statistika.class.getResourceAsStream("statistics.txt");
} catch (FileNotFoundException e) {
file = new File("statistics.txt");
}
}
How to make this work?
Try using Statistika.class.getClassLoader().getResource(filename);If it returns null then you can create new file/directory. If your accessing this from jar then use Statistika.class.getClassLoader().getResourceAsStream(filename);
Hope it will solve your problem. Let me know if you found any difficulties.
Have you tried this?
File f = new File(Statistika.class.getResource("resource.name").toURI());
if (!f.isFile()){
f.getParentFile().mkdirs();
f.createNewFile();
}
Don't do file = new File("statistics.txt"); in your catch block .. just do the following
try {
File file = new File("statistics.txt");
InputStream fis = new FileInputStream(file);
fis = Statistika.class.getResourceAsStream(file.getName());
} catch (FileNotFoundException e) {
}
This is independent of whether the file exists or not.
File f = new File("statistics.txt");
try {
f.createNewFile();
} catch (IOException ex) { }
InputStream fis = new FileInputStream(f);
Use BufferedReader to insert contents to file referenced by f.

Using File constructor with directory name starting from root

Suppose I have a .jar file that exports a temple.txt into directory ~/output. The code that does this is below. However suppose that this output folder is actually in home/workspace/temp/output. How do I use the File(..) constructor to send temple.txt to some completely different folder, such as home/Desktop/hello/ ?
public class main {
public static void main(String[] args) throws IOException {
String directory = "output";
FileWriter fstream;
BufferedWriter out;
File file = new File(directory, "temple.txt");
fstream = new FileWriter(file);
out = new BufferedWriter(fstream);
out.write(String.valueOf(1));
out.close();
}
}

Downloading files(.zip, .jar,...) to a folder

I have been trying many ways of downloading a file from a URL and putting it in a folder.
public static void saveFile(String fileName,String fileUrl) throws MalformedURLException, IOException {
FileUtils.copyURLToFile(new URL(fileUrl), new File(fileName));
}
boolean success = (new File("File")).mkdirs();
if (!success) {
Status.setText("Failed");
}
try {
saveFile("DownloadedFileName", "ADirectDownloadLinkForAFile");
} catch (MalformedURLException ex) {
Status.setText("MalformedURLException");
Logger.getLogger(DownloadFile.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Status.setText("IOException Error");
Logger.getLogger(DownloadFile.class.getName()).log(Level.SEVERE, null, ex);
}
I found this code on the net, am i using it correctly?
If i did:
saveFile("FolderName", "ADirectDownloadLinkForAFile")
I would get IOException error
What I want my code to do is:
Create folder
Download file
Downloaded file to go to the just created folder
I'm a newbie here sorry. Please help
There are various ways in java to download a file from the internet.
The easiest one is to use a buffer and a stream:
File theDir = new File("new folder");
// if the directory does not exist, create it
if (!theDir.exists())
{
System.out.println("creating directory: " + directoryName);
boolean result = theDir.mkdir();
if(result){
System.out.println("DIR created");
}
}
FileOutputStream out = new FileOutputStream(new File(theDir.getAbsolutePath() +"filename"));
BufferedInputStream in = new BufferedInputStream(new URL("URLtoYourFIle").openStream());
byte data[] = new byte[1024];
int count;
while((count = in.read(data,0,1024)) != -1)
{
out.write(data, 0, count);
}
Just the basic concept. Dont forget the close the streams ;)
The File.mkdirs() statement appears to be creating a folder called Files, but the saveFile() method doesn't appear to be using this, and simply saving the file in the current directory.

How to use this.getClass().getResource(String)?

I cant understand what the error of this code.
public void run(String url) {
try {
FileInputStream file;
file = new FileInputStream(this.getClass().getResource(url));
Player p = new Player(file);
p.play();
}catch(Exception e){
System.err.print( url + e);
}
}
when i try to run it, it says me "no suitable constructor found for FileInputStream(URL)". Why its happening?
Use:
getClass().getResourceAsStream(classpathRelativeFile) for classpath resources
new FileInputStream(pathtoFile) for file-system resources.
Put the file in root of folder of your class path (folder where your .class files are generated) and then use statements below:
InputStream inputStream =
getClass().getClassLoader().getResourceAsStream(filePath);
Player p = new Player(inputStream );
Here filePath is the relative file path w.r.t. the root folder.
It is simpler to use getResourceAsStream
InputStream in = getClass().getResourceAsStream(url);
Player p = new Player(file);
The parameter of FileInputStream constructor is File, String ... (see http://docs.oracle.com/javase/6/docs/api/java/io/FileInputStream.html ), but Class.getResource return URL (see http://docs.oracle.com/javase/6/docs/api/java/lang/Class.html), not File, or String.
Try to use
public void run(String url) {
try {
FileInputStream file;
file = new FileInputStream(new File(this.getClass().getResource(url).toURI()));
Player p = new Player(file);
p.play();
}catch(Exception e){
System.err.print( url + e);
}
}

Categories

Resources