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"));
Related
this program should print the contents of a text file called "a.txt" but with Visual Studio Code it doesn't work, reporting the error below.
I compiled with Jcreator and Geany and compile. Could anyone tell me why it doesn't work on Visual Studio Code?
import java.io.*;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Main {
public static void main (String args[]) {
//String pathFileName = "inputFile.txt";
//File inputFile = new File(pathFileName);
File inputFile = new File("a.txt");
Scanner scannerDaFile = null;
try {
scannerDaFile = new Scanner (inputFile);
System.out.println("---------------- OUTPUT TEXT: "+inputFile.getName()+" --------------------");
while(scannerDaFile.hasNextLine()) {
System.out.println(scannerDaFile.nextLine());
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
finally {
if(scannerDaFile!=null) {
scannerDaFile.close();
}
}
}
}
I had the same issue recently and turns out when you run your java from vs code your build is stored somewhere else.
In order to place the txt files where my program can find it I followed the following steps:
Print the execution dir somewhere in your code
System.out.println(System.getProperty("user.dir"));
Open add the txt files or folders into that directory.
A better way to prevent this problem to happen is to use the full path of the files.
I have created a java class to execute a batch file that is in my desktop so that the commands in the batch file will be executed too. The problem is that, i keep getting the error:
The filename, directory name, or volume label syntax is incorrect.
The filename, directory name, or volume label syntax is incorrect.
I have checked the .bat name and the directory. It is correct. When i type cmd /c start C:/Users/attsuap1/Desktop, windows explorer opens the desktop tab. However when i type cmd /c start C:/Users/attsuap1/Desktop/DraftBatchFile.bat, it gives the error. My DraftBatchFile.bat is in my desktop.
Here are my java codes:
public class OpenDraftBatchFile{
public OpenDraftBatchFile() {
super();
}
/**Main Method
* #param args
*/
public static void main(String[] args) {
//Get Runtime object
Runtime runtime = Runtime.getRuntime();
try {
//Pass string in this format to open Batch file
runtime.exec("cmd /c start C:/Users/attsuap1/Desktop/DraftBatchFile.bat");
} catch (IOException e) {
System.out.println(e);
}
}
Why is it that the batch file cannot be executed even if the directory is correct? Someone please help me. Thank you so much.
These are the codes in DraftBatchFile.bat
#echo off
echo.>"Desktop:\testing\draft.txt"
#echo Writing text to draft.txt> Desktop:\testing\draft.txt
When i execute the DraftBatchFile.bat by running the java class, i want a draft.txt file to be created in a testing folder that i have created (in desktop).
there is no such thing as desktop:\
Instead try something like this.
#echo off
echo . %userprofile%\Desktop\testing\dblank.txt
#echo Writing text to draft.txt > %userprofile%\Desktop\testing\dblank.txt
You just need to change a directory and create new subdirectory if it not exist. My offer is change .bat file like this:
#echo off
if not exist "%userprofile%\Desktop\testing" mkdir "%userprofile%\Desktop\testing"
echo.>"%userprofile%\Desktop\draft.txt"
#echo Writing text to draft.txt>"%userprofile%\Desktop\draft.txt"
Also you can create .txt file and write in it text through Java code:
File directory = new File(System.getProperty("user.home")+"//Desktop//testing");
if (!directory.exists())
directory.mkdirs();
String content = "Writing text to draft.txt";
File file = new File(System.getProperty("user.home")+"//Desktop//testing//draft.txt");
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(file));
writer.write(content);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (writer != null)
writer.close();
} catch (Exception e) {
e.printStackTrace();
}
}
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!
Background
From the examples that I've seen so far, when you read files using byte streams in java, you have to specify the file name in command prompt. I writing a Java program that I need the file name to be specified in the source code. For example:
/* Display a text file.
To use this program, specify the name of the file that you want to see.
For example, to see a file called TEST.TXT, use the following command line.
java ShowFile TEST.TXT
*/
import java.io.*;
class ShowFile {
public static void main(String args[])
throws IOException
{
int i;
FileInputStream fin;
try {
fin = new FileInputStream(args[0]);
} catch(FileNotFoundException e) {
System.out.println("File Not Found");
return;
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Usage: ShowFile File");
return;
}
// read characters until EOF is encountered
do {
i = fin.read();
if(i != -1) System.out.print((char) i);
} while(i != -1);
fin.close();
}
}
Question
Is there any way to specify the file name to read using byte streams within the source code?
The first google result for "java open file byte stream" shows you how to do this. And it's the main java documentation.
Edit:
Based on your code sample
fin = new FileInputStream("myFilenameExample");
I'm starting to code in Java in spare work time. Problem is everything is locked down and I'm kinda new to ask IT department to install ide or javac at least to me(im not in IT) so Im using Compilr.com which is quite awesome. Yet I tried to save and run the Hello world code already precoded there:
public class ReadFile
{
public static void main(String args[])
{
System.out.println("Hello World from Compilr!");
System.out.println("Press any key to continue.");
try {
System.in.read();
} catch (Throwable t) {}
}
}
Then open windows cmd and run java -jar HelloWorld.jar Which Works.
Then I tried to build and run this code which throws the typical error that I havent properly setup classpath or some manifest made:
import java.io.*;
public class ReadFile{
public static void main(String[] args){
try {
FileReader input = new FileReader(args[0]);
BufferedReader bufRead = new BufferedReader(input);
String line;
int count = 0;
line = bufRead.readLine();
count++;
// Read through file one line at time. Print line # and line
while (line != null){
System.out.println(count+": "+line);
line = bufRead.readLine();
count++;
}
bufRead.close();
}catch (ArrayIndexOutOfBoundsException e){
System.out.println("Usage: java ReadFile filename\n");
}catch (IOException e){
// If another exception is generated, print a stack trace
e.printStackTrace();
}
}// end main
}
The thing it only generates a jar file so I dont have much of choice for compiling. How do I please make working code with all the available non-core java clasess?
/At home I get error even on the helloworld program: Error:Could not find or load main class Program.
You should be able to install both JDK with Netbeans and Eclipse in a local directory without admin rights. While it will be interesting to find out why compilr.com generated jar does not work for you for any serious work you will need a development environment.