Netbeans Java: Where to put my CSV file? - java

I followed a tutorial to create some simple code to output the contents of a csv file. However, I always get the following message:
java.io.FileNotFoundException: Data.csv (The system cannot find the file specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:146)
at java.util.Scanner.<init>(Scanner.java:656)
at testing.csv.files.Test.main(Test.java:26)
BUILD SUCCESSFUL (total time: 0 seconds)
So I guess this means that the program is running, but it can't find my csv file. Basically, I just dragged and dropped it from my desktop into the "Source Packages" file in my Java Project, which is where my Test.java file is. I've also tried putting it in the "testing.csv.files", but that did not work either. Neither did putting it in the "Test Packages".
I've ran out of ideas. Where am I supposed to put this csv file?
here is my code:
package testing.csv.files;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Test {
public static void main(String[] args) {
//.csv comma separated values
String fileName = "Data.csv";
File file = new File(fileName); // TODO: read about File Names
try {
Scanner inputStream = new Scanner(file);
while (inputStream.hasNext()){
String data = inputStream.next();
System.out.println(data);
}
inputStream.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

You could try pointing to the full path of the file.
For example: String fileName = "Desktop/Data.csv";
FYI - You can copy the full path of a file by right clicking on a file while holding shift, then selecting: "copy as path".

Put your csv file(i.e Data.csv) in your project folder then it will work properly i tried your code it works fine for me

Related

How can I load/Read images in JAVA

I'm trying to load image in Java but I'm facing this error:
javax.imageio.IIOException: Can't read input file!
at java.desktop/javax.imageio.ImageIO.read(ImageIO.java:1308)
at Main.main(Main.java:10)
This is my code:
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class Main {
private static BufferedImage tmp;
public static void main(String[] args) {
try {
tmp = ImageIO.read(new File("defaults.png"));
System.out.println("reading completed ");
}catch (IOException e){
System.out.println("Error loading image ");
e.printStackTrace();
}
}
}
This specific error message is thrown when, well, the file can't be read. Check the source code of ImageIO.read():
if (!input.canRead()) {
throw new IIOException("Can't read input file!");
}
It uses the File.canRead() method to check if the file can be read. The documentation from that method say:
Returns:
true if and only if the file specified by this abstract pathname exists and can be read by the application; false otherwise
So the file you are trying to load must exists and the permission must be correct. When the exists() method returns false for your File object you know that the file you are trying to load does not exists (in the working directory you are in). When the file does indeed exists, it is a permission issue that your application are not allowed to read the file.
In a case like this, I would suggest:
Log out the absolute path of the file, to check that the system is looking for it where you think it is looking for it
Try to read the file with one of the newer file API calls (available via the Files class) which will tend to give more clueful errors us to why the file cannot be read:
File f = new File("defaults.png");
System.out.println(f.getAbsolutePath());
try {
Path p = f.toPath();
Files.readAllBytes(p);
} catch (IOException ioex) {
ioex.printStackTrace();
}

Correct path for reading lines of a file

I am new in Java and I have a question regarding the method readAlllines for the class Files. The file "Testfile.txt" is saved in the same directory as my Java class changeFiles. I want to read the lines out of it.
Here is my example code:
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
public class changeFiles {
public static void main(String[] args) {
File temp =new File("Testfile.txt");
Path p = temp.toPath();
try{
List<String> zeilen = Files.readAllLines(p);
for(String line : zeilen){
System.out.println(line);
}
} catch (IOException e) {
System.out.println(e);
}
}
}
Unfortunately, the method can't find the file. How do I get the correct path to my file in readAllLines?
You're trying to get file from working directory, check yours printing this in some way
System.getProperty("user.dir")
Place "Testfile.txt" there, run and enjoy.
Another solution will be put folder when reading file using File(folder, file) constructor:
// imagine your file is placed in: c:\tmp\Testfile.txt
final String folder = "C:\\tmp\\";
File temp = new File(folder, "Testfile.txt");
Or maybe merge both:
final String folder = System.getProperty("user.dir");
File temp = new File(folder, "Testfile.txt");
Java class location is not the same as current directory.
For example current directory is something like:
C:\Users\userName\project (This is where txt file shoud be)
And java class is something like C:\Users\userName\project\src\packageName\Java.java
to find out what the current directory is you can run: System.getProperty("user.dir")

Monitor folder for mp3

I have a homework to do and I don't know how to get started. I have to read from an external text file the paths of some random folders. I must make the paths for this folders available even I change the computer.
Then I have to output in the console the number of mp3 files found in every each folder.
My big problem is that I don't know how to make those paths work for every computer on which I run the program and also I don't know how the filter the content.
LATER EDIT: I've managed to write some code. I can search now for the mp3, but... can someone help me with this: how can i add a new path to the txt file from keyboard and also how can i remove an entire line from it?
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
String ext = ".mp3";
BufferedReader br = new BufferedReader(new FileReader("Monitor.txt"));
for (String line; (line = br.readLine()) != null;) {
findFiles(line, ext);
}
br.close();
}
private static void findFiles(String dir, String ext) {
File file = new File(dir);
if (!file.exists())
System.out.println(dir + " No such folder folder");
File[] listFiles = file.listFiles(new FiltruTxt(ext));
if (listFiles.length == 0) {
System.out.println(dir + " no file with extension " + ext);
} else {
for (File f : listFiles)
System.out.println("Fisier: " + f.getAbsolutePath());
}
}
}
import java.io.File;
import java.io.FilenameFilter;
public class FiltruTxt implements FilenameFilter{
private String ext;
public FiltruTxt(String ext){
this.ext = ext.toLowerCase();
}
#Override
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(ext);
}
}
I think that with "available even I change the computer" mean that you need to read the path from the file and not hard code it on your program so if you run in other computer you only need to change the text file and not the program.
But as #André Stannek had said in his comment, you must add to your question what have you tried and what is the exact programming problem you are facing.
When you face a problem, try to divide it in individual and more small problems. For example:
How to read a line from the console?
How to write a new line to a file?
Then try to search for a solution (if you can't think in one). For example in stack overflow, google and of course in the official documentation.
The official documentation:
http://docs.oracle.com/javase/tutorial/essential/io/index.html
Some questions in stackoverflow:
Read multiple lines from console and store it in array list in Java?
Read string line from console
How do I add / delete a line from a text file?
How to add a new line of text to an existing file in Java?
Or this links from Internet:
http://www.msccomputerscience.com/2013/01/write-java-program-to-get-input-from.html
This is the portal of the Java tutorials that you will found very useful when you are learning: http://docs.oracle.com/javase/tutorial/index.html

Saving file to certain path (Java)

When I run this as a jar, this .properties file is created on the desktop. For the sake of keeping things clean, how can I set the path to save this file somewhere else, like a folder? Or even the jar itself but I was having trouble getting that to work. I plan on giving this to someone and wouldn't want their desktop cluttered in .properties files..
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;
public class DataFile {
public static void main(String[] args) {
Properties prop = new Properties();
OutputStream output = null;
try {
output = new FileOutputStream("config.properties");
prop.setProperty("prop1", "000");
prop.setProperty("prop2", "000");
prop.setProperty("prop3", "000");
prop.store(output, null);
} catch (IOException io) {
io.printStackTrace();
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Since you are using the file name without a path, the file you creates ends in the CWD. That is the Current working directory the process inherits from the OS.
That is is you execute your jar file from the Desktop directory any files that use relative paths will end in the Desktop or any of it sub directories.
To control the absolute location of the file you must use absolute paths.
An absolute path always starts with a slash '/'.
Absolute path:
/etc/config.properties
Relative path:
sub_dir/config.properties
The simplest way is to hard code some path into the file path string.
output = new FileOutputStream("/etc/config.properties");
You can of course setup the path in a property which you can pass using the command line instead of hard coding it. The you concat the path name and the file name together.
String path = "/etc";
String full_path = "/etc" + "/" + "config.properties";
output = new FileOutputStream(full_path);
Please note that windows paths in java use a forward slash instead of back slash.
Check this for more details
file path Windows format to java format

How to remove garbage value from a file name which has been created by using createTempFile() method

I have used File.createTempFile() method to create temp file but as its output it appends the garbage value with the file name too. I used the method for uploading zipfile, but unable to delete those appended garbage value. For further functionality I need the exact name of file.
Kindly help...
Highly appreciate your response.
My concern is, as code stated by niiraj874u, I am getting the the File name : tmp4501156806082176909.txt
But I want only tmp.txt How can I remove appended numeric value?
You can use java.io.File.getName() method to get name of file..
import java.io.File;
import java.io.IOException;
public class FileDemo {
public static void main(String[] args) {
File f = null;
// creates temporary file
try {
f = File.createTempFile("tmp", ".txt", new File("D:/"));
} catch (IOException e) {
e.printStackTrace();
}
// prints name of temp file
System.out.println("File name: "+f.getName());
// prints absolute path
System.out.println("File path: "+f.getAbsolutePath());
}
}
this will print like
File name: tmp4501156806082176909.txt
File path: D:\tmp4501156806082176909.txt
It sounds like you don't need a temp file. The purpose of the "garbage" is to protect two or more instances of the app from overwriting each other. In this case use system.getProperty("java.io.temp") to get the temp dir.

Categories

Resources