Java程序辅导

C C++ Java Python Processing编程在线培训 程序编写 软件开发 视频讲解

客服在线QQ:2653320439 微信:ittutor Email:itutor@qq.com
wx: cjtutor
QQ: 2653320439
 
  
Lab 10: Reading Text Files 
 
Introduction: 
 
Files are used in many applications to provide long-term storage of important data. For example, 
most financial records in banks are stored in MySQL or Oracle database files. Images on Flickr 
and other photo sharing sites are stored in jpeg files. Video clips on Netflix and YouTube are 
stored in mpeg files. Finally, a large number of papers and documents are stored in docx or pdf 
files. All of these data files store information in pre-defined formats that can only be read or 
written by specialized applications. 
 
In this lab, we will study how Java can be used to read and process text files. One advantage of 
text files is that the data is stored in a “human readable format” by storing characters using 
ASCII codes. As we will see, the Java methods for reading data from ASCII files are very 
similar to the methods we used to read user input from the keyboard. 
 
All of the Java methods for file I/O are in the following libraries: 
• java.util.Scanner  
• java.io.FileInputStream  
• the java.io.IOException 
 
Instructions: 
 
Consider the following Java code. The main program allocates two arrays for date and price data, 
and prompts the user to enter a sequence of date price values.  When the user is finished entering 
data and hits “control-D” the data that was read into the arrays is printed to the screen. 
 
import java.util.Scanner; 
import java.io.FileInputStream; 
import java.io.IOException; 
 
public class Main 
{ 
    public static void main(String[] args) throws IOException 
    { 
        Scanner scnr = new Scanner(System.in); 
 
        // Arrays for dates and prices 
        String date[] = new String[1000]; 
        double price[] = new double[1000]; 
        int count = 0; 
         
         
 
        // Read and store dates and prices 
        System.out.println("Enter up to 1000 date and price values"); 
        System.out.println("Hit control-D when finished"); 
        while (scnr.hasNext())  
        { 
            date[count] = scnr.next(); 
            price[count] = scnr.nextDouble(); 
            count++; 
        } 
 
        // Print date and price data 
        for (int i=0; i