FileReader not working in Java - java

I'm trying to read from a file and it's not working correctly. I've looked at many examples on here and the method I'm using is borrowed from an answer to someone else's question. I'm aware you can use bufferedreader but I'd like to stick with what I know and am learning in my classes right now. When I run this code I just get a blank line, but the file contains 4 lines of information.
import java.io.*;
import java.util.Scanner;
import java.lang.StringBuilder;
import java.io.File;
import java.io.FileInputStream;
public class fileWriting{
public static void main(String[] args) throws IOException{
//Set everything up to read & write files
//Create new file(s)
File accInfo = new File("accountInfo.txt");
//Create FileWriter
Scanner in = new Scanner(new FileReader("accountInfo.txt"));
String fileString = "";
//read from text file to update current information into program
StringBuilder sb = new StringBuilder();
while(in.hasNext()) {
sb.append(in.next());
}
in.close();
fileString = sb.toString();
System.out.println(fileString);
}
}
My file contains the following text:
name: Howard
chequing: 0
savings: 0
credit: 0

One of the advantages of using something like BufferedReader over using Scanner is that you will get an exception if the read fails for any reason. That’s a good thing—you want to know when and why your program failed, rather than having to guess.
Scanner does not throw an exception. Instead, you have to check manually:
if (in.ioException() != null) {
throw in.ioException();
}
Such a check probably belongs near the end of your program, after the while loop. That won’t make your program work, but it should tell you what went wrong, so you can fix the problem.
Of course, you should also verify that accountInfo.txt actually has some text in it.

Related

FileNotFoundException for a file I know is in the directory

In the following program I am trying to read from the Hw1_1.java source code. I get a FileNotFoundException every time (probably for a good reason). I know the program isn't complete as I am just trying to stop getting the exception. I am at a loss.
If someone could point me in the right direction I would greatly appreciate it.
package hw1_1;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.Scanner;
public class Hw1_1 {
public static void main(String[] args) throws FileNotFoundException {
Scanner console = new Scanner(System.in);
System.out.println("Please enter the name of a java source code file");
String inputFileName = console.next();
String outputFileName = (inputFileName + ".txt");
try {
File inputFile = new File(inputFileName);
Scanner in = new Scanner(inputFile);
PrintWriter out = new PrintWriter(outputFileName);
while ( in .hasNextLine()) {
String line = console.nextLine();
out.println(line);
}
in .close();
out.close();
} catch (FileNotFoundException exception) {
System.out.println("File Not Found");
}
}
}
It's really a good idea - to first check the user directory of your java program. Once you know, you can easily debug the FileNotFoundException issue.
You can simply print the user directory from following code.
System.out.println(System.getProperty("user.dir")) ;
Using absolute path for the file is another way of solving problem, but that's a little irregular way of doing.
You need to be aware of path complexity in your code, especially if you are using IDE as IDE can have a different execution path
Based on your code, if the value inputFileName is just the file name (let's say log.txt) and the execution path is actually different, then your code will never find the path
The quickest and dirty solution to quickly prove this is to use the full absolute path as the value of inputFileName for example:
String inputFileName = "/var/tmp/log.txt"
or
String inputFileName = "C:/workspace/temp/log.txt"
Once this verifies that your code can read the file, then you can start handling the path issue, good luck.

Issue in reading a file with Scanner

This is a quite simple task and I have done this a lot of times. But, at the moment, I am stuck at this trivial line of code.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class Test {
private static Scanner scan;
public static void main(String[] args) throws FileNotFoundException {
// TODO Auto-generated method stub
File file = null;
switch (1) {
case 1:
file = new File("W:\\Umesoft Evobus\\From AQUA\\Aqua data_ All\\20090101-20090630_datenabzug_tilde.txt");
break;
case 2:
file = new File("W:\\Umesoft Evobus\\From AQUA\\Aqua data_ All\\20090701-20091231_datenabzug_tilde.txt");
break;
}
scan = new Scanner(file);
String x = scan.nextLine();
System.out.println(x);
}
}
When I try to read the first file, I get a NoSuchElementException. When I try to read the second file, I have no issues. Both the files are from the same source and have the same format. I am sure, there are no issues with regards to the input files. The first line in both the files are identical.
Can someone explain this situation?
The above program is just for testing. Hence, I have used a switch case to select the file.
In the actual program, a set of files are selected by the user. And every time, this file is being skipped. The input files are data files, generated through another program. They are very similar to CSV files, but the delimiter used here is ~ for some reasons. They cannot be empty, because, even in the worst case, they would have headers.
Screenshot of the file contents in notepad++:
Output for file 1:
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at controller.Test.main(Test.java:24)
Output for file 2:
Weltherstellercode~FIN~Fahrzeug_Baumuster~~Motoridentnummer~Getriebe_Identifizierungsnummer~Produktionsdatum~Produktionsnummer_Fzg~Erstzulassungsdatum~Reparaturdatum~Fahrzeug_Laufleistung_in_km~Interne_VEGA_Antragsnummer~TGA~Fehlerort~~Fehlerart~~Reparaturart~~Hauptschadensteil~Reparaturland_(G&K)~~Reparaturbetrieb_(G&K)~~Mitteilungstext~Gutschriftsdatum_(Summe)~Anzahl_Beanstandungen~Gesamtkosten~Lohnkosten~Materialkosten~Summe_DH+NK~Anzahl_Arbeitswerte_(Gutgeschrieben)
String line ="";
BufferedReader br = new BufferedReader(new FileReader("path"));
while ((line = br.readLine()) != null) {
System.out.println(line);
}
i changed previous code to use a buffered reader since
BufferedReader has significantly larger buffer memory than Scanner.
Use BufferedReader if you want to get long strings from a stream, and
use Scanner if you want to parse specific type of token from a stream
The following answer from a different post, worked.
https://stackoverflow.com/a/35173548/6234625
scan = new Scanner(file,"UTF-8");
I had to mention the encoding for the Scanner.
Thanks to everyone who tried to help me. Thanks especially to #Abhisheik and #Priyamal.

Another java.io.FileNotFoundException (The system cannot find the file specified) thread

I've created a basic notepad text file (e.g., text-file.txt) and have tried placing this file in multiple file paths for my code to retrieve, but I can't seem to get this to work. Basically, I'm wanting to take the content of text-file.txt and create a second file where everything is in all caps.
Here is my code:
package abc123;
import java.util.Scanner;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
public class abc123
{
public static void main (String [] args) throws IOException
{
Scanner in = new Scanner(System.in);
System.out.print("Please provide the name of your input file: ");
String inFileName = in.nextLine();
System.out.print("Please indicate what you'd like to name your output file: ");
String outFileName = in.nextLine();
FileReader reader = new FileReader(inFileName);
PrintWriter writer = new PrintWriter(outFileName);
Scanner fileReader = new Scanner(reader);
while(fileReader.hasNext())
{
String line = fileReader.nextLine();
line = line.toUpperCase();
writer.println(line);
}
fileReader.close();
writer.close();
System.out.println("The process is now complete. Please check your output file. Thank you.");
}
}
I'm a Java newbie, so a simple solution (and comments, as always) that I can grasp at this point would be super helpful. Thanks!
if the file isn't in the same folder as your java class, you have to give java full-path to find the file. be sure you also type the extension of the file, like ".txt".

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.

How to read a file containg just 1 line or 1 word in Java

I have a file, I know that file will always contain only one word.
So what should be the most efficient way to read this file ?
Do i have to create input stream reader for small files also OR Is there any other options available?
Well something's got to convert bytes to characters.
Personally I'd suggest using Guava which will allow you to write something like this:
String text = Files.toString(new File("..."), Charsets.UTF_8);
Obviously Guava contains much more than just this. It wouldn't be worth it for this single method, but it's positive treasure trove of utility classes. Guava and Joda Time are two libraries I couldn't do without :)
Use Scanner
File file = new File("filename");
Scanner sc = new Scanner(file);
System.out.println(sc.next()); //it will give you the first word
if you have int,float...as first word you can use corresponding function like nextInt(),nextFloat()...etc.
Efficient you mean performance-wise or code simplicity (lazy programmer)?
If it is the second, then nothing I know beats:
String fileContent = org.apache.commons.io.FileUtils.readFileToString("/your/file/name.txt")
- Use InputStream and Scanner for reading the file.
Eg:
public class Pass {
public static void main(String[] args){
File f = new File("E:\\karo.txt");
Scanner scan;
try {
scan = new Scanner(f);
while(scan.hasNextLine()){
System.out.println(scan.nextLine());
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
- Guava Library handles this beautifully and efficiently.
Use BufferedReader and FileReader classes. Only two lines of code will suffice to read one word/one line file.
BufferedReader br = new BufferedReader(new FileReader("Demo.txt"));
System.out.println(br.readLine());
Here is a small program to do so. Empty file will cause to print 'null' as output.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class SmallFileReader
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("Demo.txt"));
System.out.println(br.readLine());
}
}

Categories

Resources