简体   繁体   中英

Java Code to fetch data from a website and write it to a text file

I'm a student in my high school's AP Computer Science course, and as a final project I have to make a stock management app.

Part of this entails a process where every time the Stock app is opened, it gets the data (stock names, symbols, and current prices) on Yahoo! Finance, and writes it to a text file called Results.txt. Later, throughout the program, this file is repeatedly referred to in order to fetch names and prices.

I have code using Scanner to read a file, shown below, so I think I should be to refer to the data later, but I don't know how to go about getting the data and writing it to a file.

What java code can I use so that every time my front end code runs, it'll start by accessing Yahoo Finance and writing the stock data to the file for me to use?

Here is my method to read data from a file, into an ArrayList of Strings, line by line

public ArrayList<String> readFile(File f){
    ArrayList<String> lines = new ArrayList<String>();
    try{ 
        a = new Scanner(f);
    }catch(FileNotFoundException e){
        System.out.println("File not found");
    }

    while(a.hasNextLine())
        lines.add(a.nextLine());
    return lines;
}

F will be a file passed to it, either the results file or a transaction history file, and I intend for it to return an arraylist of lines to me. Does this work well?

For more easier usage, I recommend you write serializable object into file.

I guess that you use the java-yahoo-finance to implement your job.

In a Maven project:

  • Add following dependency,

     <dependency> <groupId>com.yahoofinance-api</groupId> <artifactId>YahooFinanceAPI</artifactId> <version>1.3.0</version> </dependency> 
  • Fetch data from web and write into file

      Stock stock = YahooFinance.get("INTC"); File file = new File(RESULT_PATH); if (!file.exists()){ file.createNewFile(); } MyStock myStock = new MyStock(); myStock.setName(stock.getName()); myStock.setSymbols(stock.getSymbol()); myStock.setPrice(stock.getQuote().getPrice().doubleValue()); ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(file)); os.writeObject(myStock); os.close(); 

Since Stock is not serializable, we create a MyStock class.

class MyStock implements Serializable{

    private String name;
    private String symbols;
    private double price;
    // setter and getter
}
  • read from file

     MyStock stock = null; try { ObjectInputStream is = new ObjectInputStream(new FileInputStream(new File(RESULT_PATH))); stock = (MyStock)is.readObject(); }catch (Exception e){ e.printStackTrace(); } return stock; 

Once you obtain the MyStock object here, you can directly handle it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM