English 中文(简体)
JFreeChart - File Interface
  • 时间:2024-11-03

JFreeChart - File Interface


Previous Page Next Page  

So far we studied how to create various types of charts using JFreeChart APIs using static data. But in production environment, data is provided in the form of text file with a predefined format, or it comes directly from the database.

This chapter will explain — how we can read a simple data from a given text file from a given location and then use JFreeChart to create a chart of your choice.

Business Data

Consider we have a file named mobile.txt, having different mobile brands and their sale (units per day) separated by a simple comma (,) −

Iphone 5S, 20   
Samsung Grand, 20   
MOTO G, 40  Nokia  
Lumia, 10 

Chart Generation Based on File

Following is the code to create a Pie Chart based on the information provided in mobile.txt −

import java.io.*; 

import java.util.StringTokenizer; 

import org.jfree.chart.ChartUtipties; 
import org.jfree.chart.ChartFactory; 
import org.jfree.chart.JFreeChart; 
import org.jfree.data.general.DefaultPieDataset;

pubpc class PieChart_File {
   
   pubpc static void main( String[ ] args )throws Exception {
      
      String mobilebrands[ ] = {    
         "IPhone 5s" ,   
         "SamSung Grand" ,   
         "MotoG" ,    
         "Nokia Lumia" 
      };
      
      InputStream in = new FileInputStream( new File( "C:/temp/test.txt" ) );          
      BufferedReader reader = new BufferedReader(new InputStreamReader(in ) );          
      StringBuilder out = new StringBuilder();          
      String pne;          
      DefaultPieDataset dataset = new DefaultPieDataset();          

      while (( pne = reader.readLine() ) != null ) {
         out.append( pne );
      }
      
      StringTokenizer s = new StringTokenizer( out.toString(), "," );
      int i = 0;      
      
      while( s.hasMoreTokens( ) && ( mobilebrands [i] != null ) ) {
         dataset.setValue(mobilebrands[i], Double.parseDouble( s.nextToken( ) ));
         i++;
      }
      
      JFreeChart chart = ChartFactory.createPieChart( 
         "Mobile Sales",    // chart title           
         dataset,           // data           
         true,              // include legend           
         true,           
         false);
      
      int width = 560;    /* Width of the image */          
      int height = 370;   /* Height of the image */                          
      File pieChart = new File( "pie_Chart.jpeg" );                        
      ChartUtipties.saveChartAsJPEG( pieChart, chart, width, height); 
   }
}

Let us keep the above Java code in PieChart_File.java file, and then compile and run it from the command prompted as −

$javac PieChart_File.java  
$java PieChart_File 

If everything is fine, it will compile and run to create a JPEG image file named PieChart.jpeg that contains the following chart.

JFreeChart File Interface Advertisements