Question

I'm writing a mock stock market in Java, and I want the ability for the user to view stocks purchased. I decided the easiest way to do this is to write to a file. My problem is that every time I run this program and attempt to read from the file, it outputs the path it took to read it. The information I want is correctly written to the file, but it isn't reading from it the way I want.

Here is the code I used for the file reading section:

if (amountOfStocks1 >= 1) {
  Scanner stocksBought1 = new Scanner("stocksbought/stocksBought1.txt");

  while (stocksBought1.hasNext()) {
    String fileRead = stocksBought1.nextLine();
    System.out.println(fileRead);
  }
  stocksBought1.close();
  runMenu = 1;
}

There are 7 of these amountOfStocks if/else statements.

I'm not sure if that's enough information. If it's not, tell me what to put on, and I'll do that.

If you can help me fix this problem or if you know an easier way to read and write to files that would be great!

Was it helpful?

Solution

Instead of:

Scanner stocksBought1 = new Scanner("stocksbought/stocksBought1.txt");

Try:

Scanner stocksBought1 = new Scanner(new File("stocksbought/stocksBought1.txt"));

When you only pass a String to the Scanner constructor the Scanner just scans that String. If you give it a File it will scan the contents of the File.

OTHER TIPS

You would probably be better off using the FileReader object. You would use code similar to the following:

import java.io.*; 
class FileReaderDemo { 
  public static void main(String args[]) throws Exception
  { 
    FileReader fr = new FileReader("FileReaderDemo.java"); 
    BufferedReader br = new BufferedReader(fr); 
    String s; 
    while((s = br.readLine()) != null) { 
        System.out.println(s); 
    } 
    fr.close(); 
  } 
}

In addition, you can use the FileWriter object to write to a file. There's lots of examples on the internet. Easy to find on simple Google search. Hope this helps.

Use FileReader.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class BufferedReaderExample {

public static void main(String[] args) {

    BufferedReader br = null;

    try {

        String sCurrentLine;

        br = new BufferedReader(new FileReader("C:\\testing.txt"));

        while ((sCurrentLine = br.readLine()) != null) {
            System.out.println(sCurrentLine);
        }

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (br != null)br.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

}
 }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top