I am java beginner learner and i am trying to output the data on file which i call a.txt. need help i have no idea y i am getting exception error file not open . i put a.txt in the same directory in which i have main and readfile.
- main path : C:\Users\Navdeep\Desktop\java\assign1\src\assign1
- readfile : C:\Users\Navdeep\Desktop\java\assign1\src\assign1
- a.txt : C:\Users\Navdeep\Desktop\java\assign1\src\assign1
Thanks in advance .
main.java
package assign1;
public class main {
public static void main(String[] args) {
readfile r = new readfile();
r.openFile();
r.readFile();
r.closeFile();
}
}
readile.java
package assign1;
import java.io.*;
import java.util.*;
public class readfile {
private Scanner x;
public void openFile() {
try {
x = new Scanner(new File("a.txt"));
} catch (Exception e) {
System.out.println("file not open \n");
}
}
public void readFile() {
while (x.hasNext()) {
String Agent = x.next();
String request_type = x.next();
String classtype = x.next();
String numberofseat = x.next();
String arrivaltime = x.next();
System.out.printf("%s %s %s %s %s \n", Agent,
request_type, classtype, numberofseat, arrivaltime);
}
}
public void closeFile() {
x.close();
}
}
a.txt
1 r e 1 0
2 r e 1 1
If you use a File with a relative path, it is assumed relative to the "current user directory". What's the "current user directory"? See the doc:
A relative pathname, in contrast, must be interpreted in terms of information taken from some other pathname. By default the classes in the java.io package always resolve relative pathnames against the current user directory. This directory is named by the system property user.dir, and is typically the directory in which the Java virtual machine was invoked.
Also from the doc:
On UNIX systems, a relative pathname is made absolute by resolving it against the current user directory. On Microsoft Windows systems, a relative pathname is made absolute by resolving it against the current directory of the drive named by the pathname, if any; if not, it is resolved against the current user directory.
So one way to get the File to be found using a relative path would be to start the JVM in the directory with the file.
However, this approach can be kind of limiting since it constrains you to always start the JVM in a certain directory.
As an alternative, you might consider using ClassLoader#getResourceAsStream. This allows you to load any resource that is on the JVM's "classpath". The classpath can be configured in a number of different ways, including at launch time using arguments to the JVM. So I would suggest using that, rather than initializing your Scanner with a File. This would look like:
InputStream is = StackOverflow.class.getClassLoader().getResourceAsStream("a.txt");
Scanner scanner = new Scanner(is);
Now, when using getResourceAsStream, you have to make sure that the file referenced is on the classpath of the Java Virtual Machine process which holds your program.
You've said in comments that you're using Eclipse.
In Eclipse, you can set the classpath for an execution by doing the following:
1) After running the program at least once, click on the little dropdown arrow next to the bug or the play sign.
2) Click on "Debug configurations" or "Run Configurations".
3) In the left sidebar, select the run configuration named after the program you're running
4) Click on the "Classpath" tab
5) Click on "User Entries"
6) Click on "Advanced"
7) Select "Add Folders"
8) Select the folder where a.txt resides.
Once you have done this, you can run the program using the run configuration you have just set up, and a.txt will be found.
Basic idea of classpath
The classpath represents the resources that the JVM (Java Virtual Machine) holding your program knows about while it's running. If you are familiar with working from a command line, you can think of it as analogous to your OS's "PATH" environment variable.
You can read about it in depth here.
Instead of putting the file in src folder put the txt file in the project ie outside the src.
Here is one using BufferedReader.
public static void main(String[] args) {
// check for arguments. this expects only one argument #index [0]
if (args.length < 1) {
System.out.println("Please Specify your file");
System.exit(0);
}
// Found atleast one argument
FileReader reader = null;
BufferedReader bufferedReader = null;
// Prefer using a buffered reader depending on size of your file
try {
reader = new FileReader(new File(args[0]));
bufferedReader = new BufferedReader(reader);
StringBuilder content = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null)
content.append(line);
System.out.println(content.toString());
} catch (IOException e) {
e.printStackTrace();
} finally {
// dont forget to close your streams
try {
if (bufferedReader != null)
bufferedReader.close();
if (reader != null)
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Let me know if you have any isues.
Good_luck_programming!
Related
i have the current code:
public void crearArchivo(String nombre) {
archivo = new File(nombre.replaceAll("\\s", "") + ".txt");
if (!archivo.exists()) {
try {
archivo.createNewFile();
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void crearCarpeta(String nombreCarpeta){
File directorio = new File(nombreCarpeta);
directorio.mkdir();
}
public void crearArchivoDatos(String nombreArchivo, ArrayList<String>datos) {
crearArchivo(nombreArchivo);
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(archivo));
for (int i = 0; i < datos.size(); i++) {
bw.write(datos.get(i));
}
bw.close();
} catch (Exception e) {
//e.printStackTrace();
}
}
the first method create a file only if it doesnt exist and the second one create a folder finally the third method save the data my problem is that i want to save some files on the folder i created first how can i set a path to save those file there, also i have the problem that this little program will execute at diferent computers so the path will change for any computer
You can get paths of folders on any computer using System.getProperty(...) - for example System.getProperty("user.home") gives you the current user directory (from which you can get to the desktop and other folders), and System.getProperty("user.dir") gives you the path of the folder from which your program is executed.
Creating or modifying files in Java can be done with the Java 8 NIO.2 methods.
Here is a link to the Oracle documentation : https://docs.oracle.com/javase/tutorial/essential/io/fileio.html
For your question, you have to declare a relative path, so it will be independent of the computer it will be executed on, rather than an absolute path, which begin on the root of the filesystem.
I have a program that works fine when it is run on eclipse (the program reads from a text file). However when it is complied and run on command line it can not find the text file I am reading from.
private void openfile()
{
try
{
file = new Scanner(new File("file.txt"));
}
catch(Exception e)
{
System.out.println("i hate command prompt");
}
private void readfile()
{
while(file.hasNext())
{
map_name = file.nextLine().split("\\s+");
}
}
private void closefile()
{
file.close();
}
can anyone explain how i can avoid this
You must place file.txt in the user.dir as specified by the File documentation. To determine what the user.dir is try printing out the property in your code, then placing the file in the directory.
System.out.println(System.getProperty("user.dir"));
This is the code I use when I try to read some specific text in a *.txt file:
public void readFromFile(String filename, JTable table) {
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new FileReader(filename));
String a,b,c,d;
for(int i=0; i<3; i++)
{
a = bufferedReader.readLine();
b = bufferedReader.readLine();
c = bufferedReader.readLine();
d = bufferedReader.readLine();
table.setValueAt(a, i, 0);
table.setValueAt(b, i, 1);
table.setValueAt(c, i, 2);
table.setValueAt(d, i, 3);
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
//Close the reader
try {
if (bufferedReader != null) {
bufferedReader.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
And it is called in this way:
readFromFile("C:/data/datafile.txt", table1)
The problem is the following: the 1st time I open the program the *.txt file I'm going to read does not exist, so I thought I could use the function exists(). I have no idea about what to do, but I tried this:
if(("C:/data/datafile.txt").exists()) {
readFromFile("C:/data/datafile.txt", table1)
}
It is not working because NetBeans gives me a lot of errors. How could I fix this?
String has no method named exists() (and even if it did it would not do what you require), which will be the cause of the errors reported by the IDE.
Create an instance of File and invoke exists() on the File instance:
if (new File("C:/data/datafile.txt").exists())
{
}
Note: This answer use classes that aren't available on a version less than Java 7.
The method exists() for the object String doesn't exist. See the String documentation for more information. If you want to check if a file exist base on a path you should use Path with Files to verify the existence of the file.
Path file = Paths.get("C:/data/datafile.txt");
if(Files.exists(file)){
//your code here
}
Some tutorial about the Path class : Oracle tutorial
And a blog post about How to manipulate files in Java 7
Suggestion for your code:
I'll point to you the tutorial about try-with-resources as it could be useful to you. I also want to bring your attention on Files#readAllLines as it could help you reduce the code for the reading operation. Based on this method you could use a for-each loop to add all the lines of the file on your JTable.
you can use this code to check if the file exist
Using java.io.File
File f = new File(filePathString);
if(f.exists()) { /* do something */ }
You need to give it an actual File object. You're on the right track, but NetBeans (and java, for that matter) has no idea what '("C:/data/datafile.txt")' is.
What you probably wanted to do there was create a java.io.File object using that string as the argument, like so:
File file = new File ("C:/data/datafile.txt");
if (file.exists()) {
readFromFile("C:/data/datafile.txt", table1);
}
Also, you were missing a semicolon at the end of the readFromFile call. Im not sure if that is just a typo, but you'll want to check on that as well.
If you know you're only ever using this File object just to check existence, you could also do:
if (new File("C:/data/datafile.txt").exists()) {
readFromFile("C:/data/datafile.txt", table1);
}
If you want to ensure that you can read from the file, it might even be appropriate to use:
if(new File("C:/data/datafile.txt").canRead()){
...
}
as a condition, in order to verify that the file exists and you have sufficient permissions to read from the file.
Link to canRead() javadoc
import java.io.FileReader;
public class SimpoTest {
public static void main(String[] args) {
FileReader fileReader = null;
try {
fileReader = new FileReader("/home/brian/Desktop/me");
int read = fileReader.read();
System.out.println((char) read);
} catch (Exception e) {
fileReader = null;
e.printStackTrace();
}
}
}
1\ echo "1" > /home/brian/Desktop/me
2\ set the breakpoint to "int read = fileReader.read();"
3\ start the debug
4\ rm -f /home/brian/Desktop/me
5\ jump to the end <======== the "1" still outputted on the console...
well...this is really weird to me. as i though there should be an exception thrown out.
can anyone give any explanation?
any comments or suggestions are appreciated.
On most Unix-like systems, a file's data remains on disk until all references go away; this includes both pathnames (hard links) and open file handles.
This is expected behavior at least on a unix-like operating system: as long as there's an open file descriptor to it, the rm'd file's blocks will remain allocated and accessible via that file descriptor.
I expect you cannot, however, open a new file descriptor to them by means of the deleted filename.
Something equivalent to this command line:
set PATH=%PATH%;C:\Something\bin
To run my application, some thing has to be in a PATH variable. So I want at the program beginning catch exceptions if program fails to start and display some wizard for user to select the installation folder of a program that needs to be in a PATH. The I would took that folder's absolute path and add it to the PATH variable and start my application again.
EDIT:
That "something" is VLC player. I need it's installation folder in PATH variable (for example: C:\Program Files\VideoLAN\VLC). My application is single executable .jar file and in order to use it, VLC needs to be in a PATH. So when the user first starts my app, that little wizard would pop up to select the VLC folder and then I would update PATH with it.
You can execute commands using the Process object, you can also read the output of that using a BufferedReader, here's a quick example that may help you out:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String args[]) {
try {
Process proc = Runtime.getRuntime().exec("cmd set PATH=%PATH%;C:\\Something\\bin");
proc.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(proc.getInputStream()));
String line = reader.readLine();
while (line != null) {
//Handle what you want it to do here
line = reader.readLine();
}
}
catch (IOException e1) {
//Handle your exception here
}
catch(InterruptedException e2) {
//Handle your exception here
}
System.out.println("Path has been changed");
}
}