Java Scanner Read from File - java

Let me first establish the following fact: I am new to java, so please be patient.
In my programming class, we were given an exercise to do at home using the Scanner class. The activity shows the following coding to exercise with:
import java.io.*;
import java.util.*;
public class FileReadWrite {
public static void main(String[] args) throws FileNotFoundException {
String[] strArr = new String[100];
int size = 0;
try {
Scanner scFile = new Scanner(new File("Names1.txt"));
while (scFile.hasNext()) {
strArr[size] = scFile.next();
size++;
}
scFile.close();
for (int i = 0; i < size; i++) {
System.out.print(strArr[i] + " ");
}
} catch (FileNotFoundException e) {
System.err.println("FileNotFoundException: " + e.getMessage());
}
}
}
The program seems to not be working correct. I use NetBeans to run the code, and when I run the code, it does not display the data in the text file, Names.txt. Why is that? The program does however Build completely without errors.
I have tried going through the Scanner class javadocs, but it's not helping me.
Please explain to me so that I can learn from the mistake made.
Thanks,
Johan

I tried your code on my mac, and it works. So I thought you might input a wrong path of Names1.txt file.
In Java, when you simply use "what_ever_file_name.txt" as the path of file, Java will only search the file in your source code folder. If nothing found, a "FILE_NOT_FOUND_EXCEPTION" will be thrown.

I agree with user2170674. I also tried your code in a Windows machine, using Eclipse, and everything went well. Maybe you are putting your file in the wrong path. Two options:
you could use the full path, like (if you're using Windows) "C:\Names1.txt";
or, a more generic solution, using JFileChooser:
// create your FileChooser
final JFileChooser chooser = new JFileChooser();
// open the FileChooser
int returnValue = chooser.showOpenDialog(null);
// if you select a file
if (returnValue == JFileChooser.APPROVE_OPTION) {
// get the file and do what you need
File file = chooser.getSelectedFile();
} else {
// throw an exception or just a message in the log...
}

Your code looks good.
Debug with a few messages.
At end, add a System.out.println() or System.out.flush().
Move exception block location to just after file use (minimise try block size) and move close() within finally block.
Make sure you view Netbeans output window (Window -> Output -> Output)
public class FileReadWrite {
public static void main(String[] args) throws FileNotFoundException {
System.out.println("##### Starting main method...");
String[] strArr = new String[100];
int size = 0;
try {
Scanner scFile = new Scanner(new File("Names1.txt"));
while (scFile.hasNext()) {
strArr[size] = scFile.next();
size++;
}
System.out.println("##### Finished scan. Found %d tokens.", size);
} catch (FileNotFoundException e) {
System.err.println("FileNotFoundException: " + e.getMessage());
} catch (Exception e) {
System.err.println("Exception: " + e.getMessage());
e.printStackTrace();
} finally {
if (scFile != null) {
scFile.close();
System.out.println("##### Closed scanner.");
}
}
System.out.println("##### Printing tokens...");
for (int i = 0; i < size; i++) {
System.out.print(strArr[i] + " ");
}
System.out.println("");
System.out.println("##### Exiting main.");
}
}

Here's a working example. Perhaps try using a BufferedReader.
import java.io.*;
import java.util.Scanner;
public class ScanXan {
public static void main(String[] args) throws IOException {
Scanner s = null;
try {
s = new Scanner(new BufferedReader(new FileReader("xanadu.txt")));
while (s.hasNext()) {
System.out.println(s.next());
}
} finally {
if (s != null) {
s.close();
}
}
}
}
From http://docs.oracle.com/javase/tutorial/essential/io/scanning.html

Related

Find line number and content of a line and then find open same line number in another file JAVA

I got this code to open up a file and getting the line number, but if I want to open up another file where the content is not the same as the first file and find the same line number, how can I do that the best way? Where do I go from here?
I'm new to this site and to Java so please go easy on me...
public class c {
public static void main(String args[]) {
File file =new File("one.txt");
Scanner in = null;
try {
int counter = 0;
in = new Scanner(file);
while(in.hasNext()) {
counter++;
String line=in.nextLine();
if(line.contains("umbrella")) {
System.out.println(line + " line: " + counter);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
You can just open the other file, and read the lines and increment a counter (counter2) until your counter2 reaches your counter-Variable (from above code-snippet). You also have to notice if the file hasn't ended.
The Code is has many similar Elements like the one you already used in your question.
The best way would depend on the context at which you are developing. You could just create additional instances of File and Scanner classes to operate on a different file as you already done in your code and mentioned in comment already.
Another method would be to create a class that would process this for you. In this case you could use this class for an unlimited number of files that you need to accomplish the same.
public class FileLineCounter {
public FileLineCounter( String filename)
{
try
{
f = new File(filename);
s = new Scanner(f);
}
catch(FileNotFoundException ex)
{
ex.printStackTrace();
}
}
public int getLineNumber( String item)
{
counter = 0;
while( s.hasNext())
{
counter++;
String line = s.nextLine();
if (line.contains(item))
{
break;
}
}
return counter;
}
private File f;
private Scanner s;
private int counter;
};
package FileUtil;
import FileUtil.FileLineCounter;
public class Main {
public static void main(String[] args)
{
String file1 = "one.txt";
String file2 = "two.txt";
FileLineCounter f1 = new FileLineCounter(file1);
FileLineCounter f2 = new FileLineCounter(file2);
System.out.println( file1 + " line : " + f1.getLineNumber("umbrella"));
System.out.println( file2 + " line : " + f2.getLineNumber("umbrella"));
}
}

Saving an ArrayList to .txt file

So, I was wondering if it's possible to save values from an ArrayList to a file, such as "inputs.txt". I've seen a question similar to this: save changes (permanently) in an arraylist?, however that didn't work for me, so I'm wondering if I'm doing something wrong. Here are my files:
Main.class
package noodlegaming.geniusbot.main;
import java.io.*;
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
import java.util.logging.Logger;
public class Main {
public static Random rand = new Random();
public static void readFileByLine(String fileName) {
try {
File file = new File(fileName);
Scanner scanner = new Scanner(file);
while (scanner.hasNext()) {
SentencesToUse.appendToInputtedSentences(scanner.next().toString());
}
scanner.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
static File inputsFile = new File("inputs.txt");
static PrintWriter printWriter = new PrintWriter(inputsFile);
public static void main(String[] args) throws IOException, InterruptedException {
if(!inputsFile.exists()) {
inputsFile.createNewFile();
}
readFileByLine("inputs.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Hello, welcome to GeniusBot. Shortly, you will be speaking with a computer that learns from what you say.");
System.out.println("Because of this circumstance, we ask that you do not type any curses, swear words, or anything otherwise considered inappropriate,");
System.out.println("as it may come back to the light at a time you don't want it to.");
System.out.println("Please note that your responses won't be saved if you close the program.");
System.out.println("If you type printInputsSoFar, a list of all the stuff you've typed will be printed.");
System.out.println("If you type printInputsLeft, the number of inputs you have left will be printed.");
System.out.println("If you type clearInputs, the program will be closed and the inputs.txt file deleted, " +
"\nand recreated upon startup.");
System.out.println("Starting up GeniusBot.");
Thread.sleep(3000);
System.out.println("Hello! I am GeniusBot!");
br.readLine();
System.out.println("" + SentencesToUse.getBeginningSentence() + "");
for (int i = 0; i < 25; i++) {
String response = br.readLine();
if (response.equals("printInputsSoFar")) {
for (int j = 1; j < SentencesToUse.inputtedSentences.size(); j++) {
System.out.println(SentencesToUse.inputtedSentences.get(j));
}
i--;
} else if (response.equals("printInputsLeft")) {
int inputsLeft = 25 - i;
System.out.println("You have " + inputsLeft + " inputs left.");
i--;
} else if (response.equals("clearInputs")) {
printWriter.close();
inputsFile.delete();
Thread.currentThread().stop();
} else {
SentencesToUse.appendToInputtedSentences(response);
printWriter.println(response);
printWriter.flush();
int inputtedSentence = Main.rand.nextInt(SentencesToUse.inputtedSentences.size());
String inputtedSentenceToUse = SentencesToUse.inputtedSentences.get(inputtedSentence);
System.out.println(inputtedSentenceToUse);
}
if (i == 24) {
System.out.println("Well, it was nice meeting you, but I have to go. \nBye.");
Thread.currentThread().stop();
printWriter.close();
}
}
}
}
SentencesToUse.class:
package noodlegaming.geniusbot.main;
java.util.ArrayList;
import java.util.List;
public class SentencesToUse {
public static String[] beginningSentences = {"What a lovely day!", "How are you?", "What's your name?"};
static int beginningSentence = Main.rand.nextInt(beginningSentences.length);
static String beginningSentenceToUse = beginningSentences[beginningSentence];
public static String getBeginningSentence() {
return beginningSentenceToUse;
}
public static List<String> inputtedSentences = new ArrayList<String>();
public static void appendToInputtedSentences(String string) {
inputtedSentences.add(string);
}
public static void clearInputtedSentences() {
inputtedSentences.clear();
}
}
As stated in the comments, use a PrintWriter to write the values to a file instead:
PrintWriter pw = new PrintWriter(fos);
for (int i = 0; i < SentencesToUse.inputtedSentences.size(); i++) {
pw.write(SentencesToUse.inputtedSentences.get(i)+"\n"); // note the newline here
}
pw.flush(); // make sure everything in the buffer actually gets written.
And then, to read them back again:
try {
Scanner sc = new Scanner(f);
while (sc.hasNext()) {
SentencesToUse.inputtedSentences.ass(sc.nextLine());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
The pw.flush(); is incredibly important. When I was first learning java, I can't tell you how many hours I spent debugging because I didn't flush my streams. Note also the "\n". This ensures that there will be a newline, and that your sentences don't just run together in one giant blob. If each one already has a newline, then that's not necessary. Unlike print vs println, there is no writeln. You must manually specify the newline character.

Compilation error: variable might not have been initialized [duplicate]

This question already has answers here:
How to avoid setting variable in a try statement
(4 answers)
Closed 8 years ago.
I'm trying to create a method that adds to a variable for each character inside a file. If the file was:
abcd
abc
ab
then after the function ran the variable it would return would be equal to 9.
Here's the code I have so far:
public static double getRow(String filename) {
double size = 0;
File f;
Scanner infile;
try{
f = new File(filename);
infile = new Scanner(f);
}
catch (IOException e){
System.out.println("Error opening the file");
//System.exit(0); not good
}
while(infile.hasNext()) {
size++;
}
infile.close();
return size;
}
But I keep getting that infile has not been initialized. I'm not sure how to get the solution I want.
Because you are initializing infile in the try block, if anything goes wrong in the try, infile will never be initialized when you attempt to use it after the catch block.
What you want to do is having all you processing in the try block, included looping through and closing infile:
public static double getRow(String filename) {
double size = 0;
File f;
Scanner infile;
try {
f = new File(filename);
infile = new Scanner(f);
while(infile.hasNext()) {
size++;
}
infile.close();
}
catch (IOException e) {
System.out.println("Error opening the file");
//System.exit(0); not good
}
return size;
}
I just tried this; the error is "variable infile might not have been initialized", which is because if there's an exception in the line new File, it wouldn't have been.
There are several solutions, but the best would be to make sure you don't try to use infile if you're not guaranteed it's been initialized, for example by putting the code inside the try block as above.
Here's my version:
import java.util.*;
import java.io.*;
class Foo {
public static double getRow(String filename) {
double size = 0;
File f;
Scanner infile ;
try{
f = new File(filename);
infile = new Scanner(f);
while(infile.hasNext()) {
size++;
}
infile.close();
return size;
}
catch (IOException e){
System.out.println("Error opening the file");
//System.exit(0); not good
}
return -1;
}
public static void main(String[] argv){
System.out.printf("ResultsL %d\n",
getRow("foo.txt"));
return ;
}
}
Ideally, you'd also make this a public static int with int size=0;, because you're counting something, which is a discrete value, not a real.

Java : Can't capture console output of a console program (Blockland.exe)

I'm trying to capture the output of a console program and write overwriting lines of the output to a file which another program will read, line by line I write into this file (the file should only contain one line at a time) but when I made this code and tried running it, it didn't work. The process started perfectly, but the file is not being created, written to, and I am not getting any System.out.println's of "Streaming : blah blah blah"
You can read the code below or use this pastebin : http://pastebin.com/raw.php?i=Yahsqxma
import java.io.*;
import java.util.Scanner;
public class OpenRC {
static BufferedReader consoleInput = null;
static String os = System.getProperty("os.name").toLowerCase();
static Process server;
public static void main(String[] args) throws IOException {
// OpenRC by Pacnet2013
System.out.println(System.getProperty("user.dir"));
if(os.indexOf("win") >= 0) {
os = "Windows";
}
else if(os.indexOf("mac") >= 0) {
os = "Mac";
}
else if(os.indexOf("nux") >= 0) {
os = "Linux";
}
switch(os){
case "Linux" : //cause I need WINE
File file = new File(System.getProperty("user.dir") + "/OpenRC.txt");
try {
Scanner scanner = new Scanner(file);
String path = scanner.nextLine();
System.out.println("Got BlocklandEXE - " + path);
String port = scanner.nextLine();
System.out.println("Got port - " + port);
scanner.close();
server = new ProcessBuilder("wine", path + "Blockland.exe", "ptlaaxobimwroe", "-dedicated", "-port" + port).start();
if(consoleInput != null)
consoleInput.close();
consoleInput = new BufferedReader(new InputStreamReader(server.getInputStream()));
streamLoop();
} catch (FileNotFoundException e) {
System.out.println("You don't have an OpenRC Config file OpenRC.txt in the directory of this program");
}
}
}
public static void streamConsole()
{
String line = "";
int numLines = 0;
try
{
if (consoleInput != null)
{
while((line = consoleInput.readLine()) != null && consoleInput.ready())
{
numLines++;
}
}
}
catch (IOException e)
{
System.out.println("There may be a problem - An IOException (java.io.IOException) was caught so some lines may not display / display correctly");
}
if(!line.equals("") && !(line == null))
{
System.out.println("Streaming" + numLines + line);
writeToFile(System.getProperty("user.dir"), line);
}
}
public static void streamLoop()
{
try
{
Thread.sleep(5000);
}
catch (InterruptedException e)
{
System.out.println("A slight problem may have happened while trying to read a command");
}
streamConsole();
streamLoop(); //it'll go on until you close this program
}
public static void writeToFile(String filePath, String content)
{
try {
File file = new File(filePath);
if (!file.exists()) {
file.createNewFile();
System.out.println("Creating new stream text file");
}
FileWriter writer = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(writer);
bw.write(content);
bw.close();
System.out.println("Wrote stream text file");
} catch (IOException e) {
e.printStackTrace();
}
}
}
You are running a DOS console application, which does not necessarily write to stdout or stderr, but it writes to the "console". It's nearly impossible to capture the "console" output reliably. The only tool that I have ever seen that is able to capture console output is expect by Don Libes, and that does all sorts of hacks.

java.util.NoSuchElementException even though input file has data

I have written this code to find out an output and i am running this using Runtime in a servlet. It shows java.util.NoSuchElementEception even though i have checked that input file has some data:
public class Sec1q10 {
static int fact(int n) {
int p = 1;
if (n != 1) {
p = n * fact(n - 1);
}
return p;
}
public static void main(String args[]) {
try {
System.out.println("first");
Scanner in = new Scanner(new FileReader("F:/sem5/algorithm/in.txt"));
String no = in.next();
int n = Integer.parseInt(no);
System.out.println(n);
int s = 0;
while (n != 0) {
s += fact(n);
n--;
}
System.out.println("sum=" + s);
String s1 = "" + s + "here";
PrintWriter out;
System.out.println(s1);
out = new PrintWriter("F:/sem5/algorithm/out.txt");
out.write(s1);
System.out.println(s1);
} catch (Exception ex) {
System.out.println("Exception: " + ex);
}
}
}
I even run this on cmd where it is showing the output without any exception but not writing anything in the file F:/sem5/algorithm/out.txt
To see results in output file close PrintWriter after writing in it
PrintWriter out;
System.out.println(s1);
out = new PrintWriter("F:/sem5/algorithm/out.txt");
try
{
out.write(s1);
System.out.println(s1);
}
finally
{
out.close();
}
Whenever you use the Scanner class you should actually test to ensure input is waiting for you before trying to read it using the hasNextXXXXX() methods.
try this:
String no;
while(in.hasNext())
{
no = in.next();
//.....
}
the problem isn't that your input file doesn't have any data, it's that your input file runs out of data because you continually read. If you try to read when nothing is there you will get a NoSuchElementException
All I can think of is that the Directory does not exist. Are you sure it does? If not, you should either make it manually, or use the .mkdir() function

Categories