Unable to read file with Scanner in Java - java

I'm attempting to pass a File object to the Scanner constructor.
File file = new File("in.txt");
try{
Scanner fileReader = new Scanner(file);
}
catch(Exception exp){
System.out.println(exp.getMessage());
}
I have an in.txt in the root of the project, src and bin directories in case I'm getting the location wrong. I have tried giving absolute paths as well. This line
Scanner fileReader = new Scanner(file);
always fails. Execution jumps to the end of main. If I misspell the name of the file, I get a FileNotFoundException. I'm on an Ubuntu 12.10 Java 1.7 with OpenJDK

I am running on linux and this is how you need to do it
import java.io.File;
import java.io.IOException;
import java.util.Scanner;
public class Testing {
public static void main(String args[]) throws IOException {
Scanner s = null;
try {
//notice the path is fully qualified path
s = new Scanner(new File("/tmp/one.txt"));
while (s.hasNext()) {
System.out.println(s.next());
}
} finally {
if (s != null) {
s.close();
}
}
}
}
here is the result :
source from Java Docs

If you do: File file = new File("in.txt"); in your java program
(let's assume it is named Program.java) then the file in.txt should
be in the working directory of your program at runtime. So if you
run your program like this:
java Program
or
java package1.package2.Program
and you are in /test1/test2/ when running this command,
then the file in.txt needs to be in /test1/test2/.

Related

Input file for JAR

I want to send the input of a jar from one file and save the output in another,
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
List<String> builder = new ArrayList<>();
String line;
while (!(line = sc.nextLine()).isBlank()) {
builder.add(line);
}
builder.stream().sorted().forEach(System.out::println);
sc.close();
}
when I execute the jar I try it like this
java -jar name.jar > output.txt < input.txt
but it generates the exception java.util.NoSuchElementException, I appreciate any help.
This is what I believe is the easiest way to accomplish what you are trying to do:
public static void main(String[] args) throws IOException {
FileWriter fw = new FileWriter("output.txt"); // Used to write to output.txt
Scanner sc = new Scanner(System.in);
List<String> builder = new ArrayList<>();
while (sc.hasNextLine()) { // Same thing as what you had, just 1 less line
// Not entirely sure what you're trying to do here;
//if no input is given at the EXACT time the program is run, this will be skipped
builder.add(sc.next());
}
builder.stream().sorted().forEach((s) -> { // Changed this to a lambda
System.out.println(s);
try {
fw.write(s);
} catch (IOException e) {
e.printStackTrace();
}
});
fw.close();
sc.close();
}
The easiest way would be to pass your input.txt file as a parameter to your jar. You can then utilize Files.readAllLines to read your text file and do your sort and then send each line to std out
Then you can redirect std out to your output.txt file.
public static void main(String[] args) throws IOException {
if (args == null || args.length == 0) throw new RuntimeException("No file provided");
Path file = Paths.get(args[0]);
if (Files.notExists(file)) throw new IOException(args[0] + " cannot be found.");
Files.readAllLines(file).stream().sorted().forEach(System.out::println);
}
Then you can invoke it like this:
java -jar name.jar input.txt > output.txt
The code is okay, not perfect, but it works. Of course your class needs to have some more lines (like defining the import and class definition etc.), but you only posted the main method is and that's okay for me.
At runtime, you're piping < input.txt as your standard input which is great.
I think your problem could be:
Your input.txt contains nothing, then you'll get this exception
Or the input.txt is in a different directory at runtime, so you're actually not piping anything as an input. There's no error from the command line, but this way you get the exception too.
One of those could be the cause.

Read an existing text file in Java

I'm a Java Beginner and I'm trying to make a program of reading from an existing text file. I've tried my best, but it keep on saying "File Not Found!". I've copied my "Test.txt" to both the folders - src and bin of my package.
Kindly help me into this. I'll be very thankful. Here's the code -
package readingandwritingfiles;
import java.io.*;
public class ShowFile {
public static void main(String[] args) throws Exception{
int i;
FileInputStream file_IN;
try {
file_IN = new FileInputStream(args[0]);
}
catch(FileNotFoundException e) {
System.out.println("File Not Found!");
return;
}
catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Usage: ShowFile File");
return;
}
do {
i = file_IN.read();
if(i != -1)
System.out.print((char)i);
} while(i != -1);
file_IN.close();
System.exit(0);
}
}
If you are just putting Test.txt then the program is looking in the root folder of the project. Example:
Project
-src
--package
---class
-bin
-Test.txt
Test.txt needs to be in the same directory as src and bin, not inside of them
If your folder structure is like this (The Text.txt file inside src folder)
+src
+Text.txt
Then use this code
ClassLoader classLoader = ShowFile.class.getClassLoader();
File file = new File(classLoader.getResource("Text.txt").getFile());
file_IN = new FileInputStream(file);
Or If your folder structure is like this
+src
+somepackage
+Text.txt
Then use this code
ClassLoader classLoader = ShowFile.class.getClassLoader();
File file = new File(classLoader.getResource("/somepackage/Text.txt").getFile());
file_IN = new FileInputStream(file);
Pass a String (or File) with the relative path to your project folder (if you have your file inside src folder, this should be "src/Test.txt", not "Test.txt").
For read a text file you should use FileReader and BufferedReader, BufferedReader have methods for read completed lines, you can read until you found null.
An example:
String path = "src/Test.txt";
try {
FileReader fr = new FileReader(path);
BufferedReader br = new BufferedReader(fr);
String line = br.readLine();
while(line != null) {
System.out.println(line);
line = br.readLine();
}
br.close();
} catch (Exception ex) {
}
Tons of ways to accomplish this! I noticed that you specify args[0], why?
// Java Program to illustrate reading from Text File
// using Scanner Class
import java.io.File;
import java.util.Scanner;
public class ReadFromFileUsingScanner
{
public static void main(String[] args) throws Exception
{
// pass the path to the file as a parameter
File file =
new File("C:\\Users\\test.txt");
Scanner sc = new Scanner(file);
while (sc.hasNextLine())
System.out.println(sc.nextLine());
}
}

Java.IO.Filenotfoundexception error, Can't find a file that exists in C:

I am recently beginning programming and cannot get my program to find a file, then read input from it. Says the file does not exist. Here is my code.
import java.util.*;
import java.io.*;
public class assignment3 {
public static void main(String args[]) throws IOException {
PrintWriter pw = new PrintWriter("C:\\file\\Summary.txt");
Scanner k = new Scanner(System.in);
String filename;
System.out.println("--------------------------------\nBowsers Nuclear Weapons Inventory\n" +
"---------------------------------");
System.out.print("Please enter the name of the file: ");
filename = k.next();
File f = new File(filename);
System.out.println(f);
Scanner inputFile = new Scanner(f);
String Game1 = inputFile.nextLine();
System.out.println(Game1);
inputFile.close();
}
}
At line Scanner inputfile = new Scanner(f);. The error mentioned appears. Also when prompted to type in the file name in the program, i put "C:/Games.txt".....but when i got the filename to be printed out the filename is registerd as C:\Games.txt....why is the forward slash turning into a backslash. Thank you for taking the time to help me.
Make sure the folder named "file" exists (for creating a file). It might throw that error if it's not there. For reading you need to have the proper rights.
why is the forward slash turning into a backslash?
Because you're on Windows, and directories are natively separated by a \
Next, you don't appear to be writing with your PrintWriter. And if you want to check for a file that exists, call File#exists().
File f = new File(filename);
if (f.exists()) {
System.out.println(f);
Scanner inputFile = new Scanner(f);
while (inputFile.hasNextLine()) {
System.out.println(inputFile.nextLine());
}
} else {
System.out.println(f.getPath() + " does not exist");
}
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class Answer {
public static void main(String args[]) throws IOException, FileNotFoundException {
// Have to throw a FileNotFoundException just in case an error occurs the compiler needs to know how to process the error.
PrintWriter pw = new PrintWriter("C:/file/Summary.txt");
Scanner k = new Scanner(System.in);
String filename;
System.out
.println("--------------------------------\nBowsers Nuclear Weapons Inventory\n"
+ "---------------------------------");
System.out.print("Please enter the name of the file: ");
filename = k.nextLine(); //Input for strings
System.out.println(filename);
File f = new File("C:/file/"+filename+".txt"); //Must have a location for your files
f.createNewFile(); //The file's pathname is the only thing that you can supply when you instantiate the object
//you actually have to invoke the createNewFile method upon the object.
if(f.exists()) { //Don't be afraid to check your code this is a must for every programmer.
System.out.println("Good! The File Exists");
}
Scanner inputFile = new Scanner(f);
String Game1 = inputFile.nextLine();
System.out.println(Game1);
inputFile.close();
}
}
When you create a file you always have to throw a FileNotFoundException if you do not the compiler will not know what to do if the error occurs. Use / when specifying directories of files.
\ is generally used as an escape sequence and when you type this \ \ your basically telling it to escape itself this code is useful in other situations but not this one.
You can NOT create a new file by the initiation of the object you always have to invoke the createNewFile method upon the object so that you can create a new file. This is because no constructors automatically call the createNewFile method in the class. You might be wondering what the words in the parameter are, they just serve the purpose of naming the file directory. I have found a helpful link if you want to review creating Files. Just look under the constructors tab. API Files Class
BE SURE! to always check your code, it does not matter how good of a programmer you are. You ALWAYS have to check for errors and if you make a game, and don't know where the error is among the millions of lines of code. You are going to have a hell of a time.
Lastly, I was not sure what you were trying to do after the if statement, but you will receive an error after the if statement, so if you want to ask me how to help with that just type in the comments of my post.

Always getting FileNotFoundException in java

I am using Scanner to read the File contents. For that I am using the following code.
public static void main (String[] args) throws IOException {
File file = new File("/File.txt");
Scanner sc = new Scanner(file);
while(sc.hasNextLine()) {
// Until the end
System.out.print(sc.nextLine());
}
sc.close();
}
But this code always throws FileNotFoundException. I have tried Googling this, but I can't find where to check the file. Secondly, I have created files with same name in almost every directory to check when would the Code catch the presence of file.
You can see in the Package I have created a file named File.txt so that code can find it whereever it looks for.
In the Java docs, I get to know that the File accepts a String parameter as
File file = new File("file_name");
But what sort or what would be the param here, isn't told. Can I get the help?
I think you want File file = new File("File.txt"); instead of File file = new File("/File.txt");, get rid of the slash. If what you want is a relative path, you want .\File.txt
As #deterministicFail says in the comments, it is not a good idea to hardcode path separators, instead use System.getProperty("path.separator"); This way your code should work in multiple plataforms, so your code would be:
To make it plataform independent (Asuming you are using a relative path):
File file = new File("." + System.getProperty("path.separator") + "File.txt");
Replace the line
File file = new File("/File.txt");
with
File file = new File(".\\File.txt");
or
File file = new File("File.txt");
File f=new File("testFile.txt");
For this kind of referral you need to put file in root of your eclipse project (In parallel of src). This problem is only when you are Using Eclipse IDE.
Best solution for this kind of problems is checking AbsolutePath of the file
System.out.println(f.getAbsolutePath());
It will give you path where your code is looking for file.
There are two possibilities if you are looking for the file in the working directory then either use "File.txt" or "./File.txt". In case of windows one more option would be to use ".\File.txt).
If that is not what you are looking for, you can check which path the file refers to using either of the two sysouts immediately after instantiating the file, which will give you the absolute path on your machine.
File f = new File("/File.txt");
System.out.println(f.getAbsolutePath());
System.out.println(f.getAbsoluteFile().getAbsolutePath());
I have never done it the way you did but this is how I read files.
This is the purpose of the class FileInpuStream. I use a buffer to get bytes.
If it is only a problem of path, why don't you simply use the complete path ? You can copy paste it from the file information.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
FileInputStream fis = null;
try {
// object I use to read files
fis = new FileInputStream(new File("File.txt"));
byte[] buf = new byte[8];
int n = 0;
// while there is something in the file
while ((n = fis.read(buf)) >= 0) {
for (byte bit : buf) {
// do what you want
System.out.print("\t" + bit + "(" + (char) bit + ")");
System.out.println("");
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (fis != null)
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Try not to use the / in File.txt, and if you really have to, use the backslash instead \ since you're in Windows

Modify or Delete Data in a File

Today I was trying the algorithm for modifying and deleting data inside a file using Java in Windows platform.
1st : create a temporaryFile
2nd : write the data you wanted inside the originalFile into a String and to the temporaryFile
3rd : rename temporaryFile to originalFile.
The Code:
import java.io.File;
import java.io.IOException;
import java.io.FileWriter;
import java.util.Scanner;
import java.io.FileNotFoundException;
public class testing{
private static String temp;
public static void main(String [] args)
{
try{
File tempFile = File.createTempFile("haha\\temporary", ".txt"); //create a temporary file in haha folder
FileWriter writer = new FileWriter(tempFile);
Scanner input = new Scanner(new File("haha\\testing.txt")); //get input from testing.txt
temp = input.next();
writer.write(temp);
writer.close();
File origFile = new File("haha\\testing.txt");
tempFile.renameTo(origFile);
}
catch ( FileNotFoundException fileNotFoundException ){}
catch(IOException ioException){}
}
}
In the above code , the textFile to be edited is located inside a folder name haha which is located inside another folder together with the testing.class.I've tried this code to no avail , the originalTextFile has no changes .
If you have your file in the same directory, you don't need to pass the path to the File constructor.
Scanner input = new Scanner(new File("testing.txt"));
This should do it.
You need to close the Scanner object to make the changes, the underlying operating system has a file lock that must be released.
input.close();
File origFile = new File("haha\\testing.txt");

Categories

Resources