PrintWriter eclipse - java

I'm using Eclipse to write code that needs to write to an output file. the file name comes from a command-line argument. I don't know where it is creating the file. It says that my workspace is the default for the output file but it is no where to be found. This is my code
try{
PrintWriter output = new PrintWriter(new File(args[3]));
//System.out.print(args[3]);
output.append('l');
output.close();
} catch(IOException e) {
System.exit(0);
}

Add the following to your program to see the absolute path of the file.
File file = new File(args[3]);
System.err.println( "File: " + file.getAbsolutePath() );

Related

Java - File IO - AbsolutePath() does not return the path to the file

I have been trying to get this method working for the past few days always coming back to the same problem. My file won't open unless the file path is specified and formatted.
This is my code:
text = new MyArrayList<>();
String filePath = new File(fileName).getAbsolutePath();
filePath = filePath.replace('\\', '/');
try {
Scanner s = new Scanner(new File(filePath));
while (s.hasNext()) {
text.add(s.next());
}
s.close();
}
catch(FileNotFoundException e){
System.out.println("File not found.");
}
For some reason when I invoke the getAbsolutePath(), it gives me this path : "C:/Zaid/College/CE2336/Programs/File.txt"
whereas the file path that actually allows me to access the file is:
"C:/Zaid/College/CE2336/Programs/MyImplementations/File.txt"
I don't understand what I should do to clean this up.
P.S. The MyImplementations is the package where the text file and my code reside in.
When you call
String filePath = new File(fileName).getAbsolutePath();
you are creating file in your root directory of the project and then getting that path instead of the file you already have and want to get
This should be sufficient in your case:
Scanner s = new Scanner(new File(fileName));
Also ensure when handling errors you share all the information you have: Print the file that was not found. You will see that this makes troubleshooting just so much easier.
catch(FileNotFoundException e){
System.out.println("File not found.");
e.printStackTrace(System.out);
}

Printing to .txt file in java not working

I am wanting to store some variables in a .txt file for storage and have attempted to use the PrintWriter functions, however the txt file i am trying to create doesn't actually create, let alone write to the file!
Code:
if(new String("SimpleBLEBroadcaster").equals(result.getDevice().getName()))
peripheralTextView.append("Device Name: " + result.getDevice().getName() + " rssi: " + result.getRssi() +" Packet length: " + PacketLength + " Packet Data: " + "0x" + R + "\n");
File myObj = new File("C:\\Users\\Josh Gascoigne\\Documents\\Uni stuff\\Android Studio\\Data.txt");
PrintWriter DataOut = null;
try {
DataOut = new PrintWriter("Data.txt");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
DataOut.println(R);
DataOut.close();
I have followed a few tutorials on how best to use the print writer function and copied a youtube tutorial but using my variables and i cant understand why the txt file isnt being created. i even tried generating the file prior to writing to it. Any help would be much appreciated.
Your constructor for PrintWriter should be as follows;
DataOut = new PrintWriter(myObj);
Refer: PrintWriter
----------------Explanation-----------------
What your code is doing is that the PrintWriter is not referring to the same file that you are instantiating in the code above.
File myObj = new File("C:\Users\Josh Gascoigne\Documents\Uni stuff\Android Studio\Data.txt");
What you code is possibly doing is creating a new file Data.txt in the working directory of the program.
So basically, you referring to the file C:\\Users\\Josh Gascoigne\\Documents\\Uni stuff\\Android Studio\\Data.txt is redundant.
Referring to the variable myObj in the PrintWriter constructor should fix that redundancy. (Provided that is what your use case is.)
There's no such path as c:\ on any Android device.
Then your print writer too.
You didn't even specify any path.
At least try something like
File destination = new File(getExternalFilesDir(null), "data.txt");
Dataout = new PrintWriter(destination);
Dataout.println(R);
Dataout.close();

JAVA - File I/O cant get file to read

I'm trying to get inventory.csv to load in Eclipse, and I'm not sure where I'm supposed to put the location of the file (Example: c:\\Users\\...) or if I even need it, considering it's in the same folder. I recieved an "unable to load inventory.csv." output. My driver finishes the rest of the program with no errors afterwards.
public int readInventory(Automobile[] inventory)
{
final String FILENAME = "inventory.csv";
int size = 0;
Scanner input = new Scanner("inventory.csv");
try
{
input = new Scanner(new File(FILENAME));
}
catch (FileNotFoundException e)
{
System.out.println("Unable to open file " + FILENAME + ".");
}
// ...
return size;
}
Here is the output I'm getting with no syntax errors.
Unable to open file inventory.csv.
considering it's in the same folder.
Same folder as what? inventory.csv was not present in the current working directory when you executed your program.
If you are trying to read a CSV file from a single Java program then directly keep your file in the same location where the class was created.
In eclipse, keep the CSV file directly under your project directory. As you can see, the Employee.xml file directly under JavaPrac project.enter image description here
You should try this
try{
FileReader fr=new FileReader(filename);
BufferedReader br =new BufferedReader(fr)
String lime=br.readLine();
br.close();
catch(Exeption e){}

Java Scanner(System.in) does not open file after user input

Hello there I am facing an issue which I cannot find a solution. I am asking the user to input the name of a file but the output i get is always ''unable to open file''. Any advice would be much appreciated.
Scanner reader = new Scanner(System.in);
System.out.println("Enter the name of textfile to be read ( add .txt): ");
String fileName = reader.next();
String line = null;
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
catch(FileNotFoundException ex) {
System.out.println(
"Unable to open file '" +
fileName + "'");
}
catch(IOException ex) {
System.out.println(
"Error reading file '"
+ fileName + "'");
// Or we could just do this:
// ex.printStackTrace();
}
}
The FileNotFoundException is always executed but why?
P.S if I change the path to a specific location such as "C:\etc" it reads the file.
If you don't specify the absolute file path, ie, C:/dir/..., java will look in the same directory as the project root (the same directory as your src and bin folders). If the file is there, it will find it with just the file name, or if you make a directory in that folder, you would need that directory in the path. The same is true if you have an executable JAR, it will look in the same directory that the JAR is located.
If you only give the file name and not the path, Java doesn't know where to look. If you are certain that the file will be in the project directory, just prepend C:/etc to the user input.

Java.io.FileNotFoundException using File object

File read = new File("Numbers.txt");
Scanner inputFile = new Scanner(read);
while(inputFile.hasNext())
{
sum = inputFile.nextDouble() + sum;
count++;
}
inputFile.close();//close the input file
I'm trying to read data out of the text file Numbers.txt and the following code compiles fine but I get the Java.io.FileNotFoundException error when the program runs. I've also tried entering the full file path but I might have done it wrong. Any ideas?
Make Sure your text file is in the folder with your java file
because you used the direct path .
and try this code check, if still not working .
BufferedReader read = new BufferedReader(new FileReader("yourTextFile.txt"));
String line = read.readLine();
while(line !=null)
{
System.out.println(line);
line=read.readLine();
}
}catch(Exception ex)
{System.out.println(ex.getMessage());}
Try adding
System.out.println("Full path is " + read.getCanonicalPath()
+ ", canRead=" + read.canRead()
+ ", exists=" + read.exists());
and then see whether the full path exists on your file system, and whether it is readable according to canRead.
If the file is a symlink, canRead might return true in that the symlink is resolvable even though the file to which the link points is unreadable. To deal properly with symlinks you really need to use the new java.nio.file APIs.

Categories

Resources