java: Visual Studio Code doesn't read file - java

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.

Related

Java-Selenium: Eclipse is unable to find my file, but my file is in its working directory

I am using Eclipse and the Java Library: java.io.FileInputStream;
My script cannot find a file that I want to assign to a variable using the constructor FileInputStream even though the file is in the Working directory.
Here is my code:
package login.test;
import java.io.File;
import java.io.FileInputStream;
public class QTI_Excelaccess {
public static void main(String [] args){
//verify what the working directory is
String curDir = System.getProperty("user.dir");
System.out.println("Working Directory is: "+curDir);
//verify the file is recognized within within the code
File f = new File("C:\\\\Users\\wes\\workspace\\QTI_crud\\values.xlsx");
if (f.exists() && !f.isDirectory()){
System.out.println("Yes, File does exist");
} else {
System.out.println("File does not exist");
}
//Assign the file to src
File src = new File("C:\\\\Users\\wes\\workspace\\QTI_crud\\values.xlsx");
System.out.println("SRC is now: "+src);
//Get Absolute Path of the File
System.out.println(src.getAbsolutePath());
FileInputStream fis = new FileInputStream(src);
}*
My output is (when i comment out the last line) is
"Working Directory is: C:\Users\wes\workspace\QTI_crud
Yes, File does exist
SRC is now: C:\Users\wes\workspace\QTI_crud\values.xlsx
C:\Users\wes\workspace\QTI_crud\values.xlsx"
When I don't comment out the last line, I get the error:
"Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Unhandled exception type FileNotFoundException
at login.test.QTI_Excelaccess.main(QTI_Excelaccess.java:30)"
Where have I gone wrong in my code? I'm pretty new to Java
Much thanks!
Major problem with the code is that you after you know that file do not exist on specified directory, you tried to read the file. Hence, it is giving you the error.
Refactor it to this
if (f.exists() && !f.isDirectory()){
System.out.println("Yes, File does exist");
try {
FileInputStream fis = new FileInputStream(f);
//perform operation on the file
System.out.println(f.getAbsolutePath());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
System.out.println("File does not exist");
}
Here as you can see, if file exists then you try to read the file. If it is not available you don't do anything.

being able to read a file on command file using java

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"));

FileInputStream("hello.txt"), doesn't work unless I specify an absolute path (C:\User\Documents etc)

Hi is there any way I can get FileInputStream to read hello.txt in the same directory without specifying a path?
package hello/
helloreader.java
hello.txt
My error message: Error: .\hello.txt (The system cannot find the file specified)
You can read file with relative path like.
File file = new File("./hello.txt");
YourProject
->bin
->hello.txt
->.classpath
->.project
Here is works
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class fileInputStream {
public static void main(String[] args) {
File file = new File("./hello.txt");
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
System.out.println("Total file size to read (in bytes) : "
+ fis.available());
int content;
while ((content = fis.read()) != -1) {
// convert to char and display it
System.out.print((char) content);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null)
fis.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
You can use YourClassName.class.getResourceAsStream("Filename.txt"), but your text file has to be in the same directory/package as your YourClassName file.
When you open "hello.txt" you are opening a file in the current working directory of the process. i.e. where the program was run from, not where your jar is or some other directory.
When you open your file with path hello.txt, the file hello.txt should be in the same directory of where you execute the java command, that is the working directory. And you can use the following code to print the working directory when you run a Java program:
System.out.println(System.getProperty("user.dir"));
Suppose you execute your code like this java hello.helloreader, then you should use the following path to get the hello.txt:
new FileInputStream("hello/hello.txt")
you can try System.getProperty("dir") to show your current directory, and you will know how to write your file path

How to run compilr.com java .jar executable on windows when its not just java.lang* package

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.

How can I set/update PATH variable from within java application on Windows?

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");
}
}

Categories

Resources