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.
Related
I am creating a program which creates reads a file into an array separating which file into a different index value in the array.
static String[] readFile () {
int count = 0;
try {
File file = new File("input.txt"); // create file
Scanner scanner = new Scanner(file); // create scanner associated to file
// counts number of lines
while (scanner.hasNextLine()) {
scanner.nextLine();
count++;
}
// reads file into array
while (scanner.hasNextLine()) {
String[] data = new String[count];
int len = data.length;
for (int i = 0; i <= len; i++) {
data[i] = scanner.nextLine();
}
}
} catch (Exception e) {
System.out.println("File not found!!!");
System.exit(0);
}
return data;
}
The problem is that when trying to return the variable data I get an error saying 'cannot resolve symbol data" because it is initialized in a try-catch block. I have tried doing this but it returns the value null because the variable's length is determined by the variable count whose's value is also determined in a catch block. Thanks in advance!
You can use #Sweeper advice from comments. It will be looks like this.
static ArrayList<String> readFile () {
ArrayList<String> data = new ArrayList<>();
try {
File file = new File("input.txt"); // create file
Scanner scanner = new Scanner(file); // create scanner associated to file
while (scanner.hasNextLine()) {
data.add(scanner.nextLine()) ;
}
} catch (Exception e) {
e.printStackTrace();
}
return data;
}
But if you want to stay with your current code, you can initialize data by null out of try block. And also you need to reset Scanner. Your code will be looking something like this. Note, that in the for loop you must use condition <len not <=len.
static String[] readFile () {
String[] data = null;
try {
File file = new File("input.txt"); // create file
Scanner scanner = new Scanner(file); // create scanner associated to file
// counts number of lines
int count = 0;
while (scanner.hasNextLine()) {
scanner.nextLine();
count++;
}
scanner.close(); // don't forget about closing resources
data = new String[count];
// reads file into array
scanner = new Scanner(file);
for (int i = 0; i < len; i++) {
data[i] = scanner.nextLine();
}
scanner.close();
} catch (Exception e) {
e.printStackTrace();
}
return data;
}
Here are some similar questions with answers:
Java: Reading a file into an array
Read text file into an array
Also, I want to point at the try-with-resources statement - the Scanner object should be closed or initialized inside it.
Additionally, System.exit(0); is not a good way to stop a method, because all finally blocks around it wouldn't be executed in this case.
you are having 2 problems the firsthappens because the variable data is declared in the try-catch block ¿what if an instruction throws an exeption and the variable data is never declared? in this case ¿what is going to be returned?, the solution is to declare the variable data before the try-catch block, the second happens because when you invoke nextLine() the Scanner object mantains its state so when you try to invoke nextLine() again after go through the whole file it is in the last line (there is not next line), you can solve it invoking close() and then initialize the scanner object again this will reset the state:
static String[] readFile () {
Scanner scanner = null;
int count = 0;
String[] data = null;
try {
File file = new File("C:\\Users\\Mulé\\Desktop\\doc.txt"); // create file
scanner = new Scanner(file); // create scanner associated to file
// counts number of lines
while (scanner.hasNextLine()) {
scanner.nextLine();
count++;
}
scanner.close();
scanner = new Scanner(file);
// reads file into array
data = new String[count];
for (int i = 0; i < data.length; i++) {
data[i] = scanner.nextLine();
}
} catch (Exception e) {
System.out.println("File not found!!!");
System.exit(0);
}
return data;
}
I don't know how to write this line: +print(cArray: char[]): void . I know what I want to do for my homework problem, it's just this array line that the book did a lousy job explaining. If you want to know the problem: Write a program to create a file named Excercise12_15.tx if it does not exist. Write 100 integers created randomly into the file using the test I/O. Integers are seperated by spaces in the file. Read the data back from the file and display the data in increasing order.
package WriteReadData;
import java.util.*;
public class WriteReadData {
public static void main(String[] args) throws Exception
{
java.io.File file = new java.io.File("Excercise12_15.txt");
final int SIZE = 100;
int [] emptyArray = new int[SIZE];
if ( file.exists())
{
System.out.print("File exists");
System.exit(0);
}//end if
try
{
java.io.PrintWriter output = new java.io.PrintWriter(file);
for (int i = 1; i < SIZE; i++)
{
emptyArray[i] = (int)(Math.random() * 100);
output.print(emptyArray: int[]): void
}//end for
}//end try
catch
{
output.close();
}//end catch
}//end main
}//end class
java.io.File file = new java.io.File("C:/Users/someUser/Desktop/Excercise12_15.txt");
final int SIZE = 100;
int [] emptyArray = new int[SIZE];
if ( file.exists())
{
System.out.print("File exists");
System.exit(0);
}//end if
//Place your output variable up here, so that it could be seen in the catch and finally block.
java.io.PrintWriter output = null;
try
{
output = new java.io.PrintWriter(file);
for (int i = 1; i < SIZE; i++)
{
emptyArray[i] = (int)(Math.random() * 100);
//Your issuse was here, you didn't write the array to the file correctly
output.print(emptyArray[i] + " ");
}//end for
}//end try
catch (Exception ex)
{
System.out.println(ex.getMessage());
}//end catch
finally{
//Don't place the close in the catch block, do it in the finally, because it always
//executes even when a catch happens.
output.close();
}
}
This is how to properly write the array to a text file with spaces.
I am trying to make a scoring system for a game I'm writing, but I need to be able to read an integer variable from a text document. I can easily get a String variable, but it won't come in as an integer. How would I go about doing that? Here is the code I have for reading and writing the score, but the input won't come in as an integer, as you can see when the println outputs the value of score2 integer. Thanks! I'm using an eclipse IDE for Java by the way.
import java.io.*;
public class ClassName {
public static void main(String[] args) {
FileOutputStream output;
FileInputStream input;
in score = 10;
int integer = 4;
try {
output = new FileOutputStream("score.txt");
new PrintStream(output).println(score);
output.close();
} catch (IOException e) {}
try {
input = new FileInputStream ("score.txt");
int score2 = (new DataInputStream(score).readLine());
input.close();
System.out.println(score2);
} catch (IOException e) {}
}
}
}
I would use a Scanner and try-with-resources,
try (Scanner sc = new Scanner(new File("score.txt"))) {
int score2 = sc.nextInt();
System.out.println(score2);
} catch (IOException e) {
e.printStackTrace();
}
To convert string to int you can use Integer.parse method
What you want to do is called parsing.
You want to use the parseInt() method of the Integer java class (link to doc)
try{
Integer.parseInt(new DataInputStream(score).readLine())
} catch (NumberFormatException e) {
}
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
This question already has an answer here:
Reading a File From the Computer
(1 answer)
Closed 8 years ago.
I'm trying to read a file from the computer that is in the same folder as the source code and when I run the code is saying: File does not exist
Can you help me ?
import java.io.*;
import java.util.*;
public class Lotto1 {
static String[][] arr;
static String name, number;
public static void main(String[] args) throws IOException {
File f = new File("D:\\Filipe\\Project Final\\src\\database_lotto.txt.txt");
Scanner s;
try {
s = new Scanner(f);
BufferedReader reader = new BufferedReader(new FileReader(f));
int lines = 0;
while(reader.readLine() != null) {
lines++;
}
reader.close();
arr = new String[lines][3];
int count = 0;
//while theres still another line
while(s.hasNextLine()) {
arr[count][0] = s.next() + "" + s.next();
arr[count][1] = s.next();
arr[count][2] = s.next();
count++;
}
} catch(FileNotFoundException ex) {
System.out.println("File does not exist");
}
I've inferred what you're trying to do and recoded it, but this implementation will read the file if it is where you say it is.
public static void main(String[] args) {
final String filename = "database_lotto.txt";
final File lottoFile = new File(filename);
try (final Scanner scanner = new Scanner(lottoFile)) {
final List<String[]> storage = new ArrayList<String[]>();
while (scanner.hasNextLine()) {
storage.add(scanner.nextLine().split(" "));
}
}catch (FileNotFoundException ex) {
System.out.println("File not found :(");
}
}
Are you on Unix/Linux machine?
It is better to use File.separator instead of \, because File.separator uses the system char for a directory (\ on Win, / on Linux etc.)
Use File.exists() to check if file is there, before using it.