I'm trying to create program downloads historical data from Yahoo Finance and then displays the historical data for the last year based a stock symbol entered into the main class.
For some reason, I keep getting a 401 code when I try to run my program. The URL displayed in the 401 error gets me where I want to go if I copy and paste into a browser.
Not sure what I am doing wrong here.
Here's my code for the StockDownloader Class:
import java.util.GregorianCalendar;
import java.util.Calendar;
import java.util.ArrayList;
import java.net.URL;
import java.net.URLConnection;
import java.util.Scanner;
public class StockDownloader
{
public static final int DATE = 0;
public static final int OPEN = 1;
public static final int HIGH = 2;
public static final int LOW = 3;
public static final int CLOSE = 4;
public static final int VOLUME = 6;
public static final int ADJCLOSE = 5;
private ArrayList<GregorianCalendar> dates;
private ArrayList<Double> opens;
private ArrayList<Double> highs;
private ArrayList<Double> lows;
private ArrayList<Double> closes;
private ArrayList<Integer> volumes;
private ArrayList<Double> adjCloses;
public StockDownloader (String symbol)
{
dates = new ArrayList<GregorianCalendar>();
opens = new ArrayList<Double>();
highs = new ArrayList<Double>();
lows = new ArrayList<Double>();
closes = new ArrayList<Double>();
volumes = new ArrayList<Integer>();
adjCloses = new ArrayList<Double>();
//https://query1.finance.yahoo.com/v7/finance/download/IBM?period1=1467352800&period2=1498888800&interval=1d&events=history&crumb=2WsiR.p1KtI
String url = "https://query1.finance.yahoo.com/v7/finance/download/"+symbol+"?period1=1467352800&period2=1498888800&interval=1d&events=history&crumb=2WsiR.p1KtI";
try
{
URL yhoofin = new URL(url);
URLConnection data = yhoofin.openConnection();
Scanner input = new Scanner(data.getInputStream());
if(input.hasNext())//skip line...it's just the header
input.nextLine();
//start reading data
while(input.hasNextLine())
{
String line = input.nextLine();
//TODO- connec tdata to the correct ArrayList
System.out.println(line);
}
}
catch (Exception e)
{
System.err.println(e);
}
}
public ArrayList<GregorianCalendar> getDates()
{
return dates;
}
/*public ArrayList<Double> get Opens()
{
}*/
}
And my code for the main class:
public class Stocks {
public static void main(String[] args)
{
StockDownloader test = new StockDownloader("DCTH");
}
}
Help please
Looks like yahoo has changed the mode of ways of accessing finance API. You need to add a cookie to URL connection. Have changed your code and it works for me.
public class StockDownloader {
public static final int DATE = 0;
public static final int OPEN = 1;
public static final int HIGH = 2;
public static final int LOW = 3;
public static final int CLOSE = 4;
public static final int VOLUME = 6;
public static final int ADJCLOSE = 5;
private ArrayList<GregorianCalendar> dates;
private ArrayList<Double> opens;
private ArrayList<Double> highs;
private ArrayList<Double> lows;
private ArrayList<Double> closes;
private ArrayList<Integer> volumes;
private ArrayList<Double> adjCloses;
private String finalCrumb;
public StockDownloader(String symbol) {
dates = new ArrayList<GregorianCalendar>();
opens = new ArrayList<Double>();
highs = new ArrayList<Double>();
lows = new ArrayList<Double>();
closes = new ArrayList<Double>();
volumes = new ArrayList<Integer>();
adjCloses = new ArrayList<Double>();
try {
// Hit the below URL to get the cookies and the crumb value to access the finance API
String mainURL = "https://uk.finance.yahoo.com/quote/"+symbol+"/history";
Map<String, List<String>> setCookies = setCookies(mainURL);
// https://query1.finance.yahoo.com/v7/finance/download/IBM?period1=1467352800&period2=1498888800&interval=1d&events=history&crumb=2WsiR.p1KtI
// will need to append the crumb in the end to the below URL to have the actual crumb rather than the hardcoded one
String url = "https://query1.finance.yahoo.com/v7/finance/download/" + symbol
+ "?period1=1467352800&period2=1498888800&interval=1d&events=history&crumb=" + finalCrumb;
URL yhoofin = new URL(url);
URLConnection data = yhoofin.openConnection();
// get the list of Set-Cookie cookies from response headers
List<String> cookies = setCookies.get("Set-Cookie");
if (cookies != null) {
for (String c : cookies)
data.setRequestProperty("Cookie", c);
}
Scanner input = new Scanner(data.getInputStream());
if (input.hasNext())// skip line...it's just the header
input.nextLine();
// start reading data
while (input.hasNextLine()) {
String line = input.nextLine();
// TODO- connec tdata to the correct ArrayList
System.out.println(line);
}
input.close();
}
catch (Exception e) {
System.err.println(e);
}
}
// This method extracts the crumb and is being called from setCookies() method
private String searchCrumb(URLConnection con) throws IOException {
String crumb = null;
InputStream inStream = con.getInputStream();
InputStreamReader irdr = new InputStreamReader(inStream);
BufferedReader rsv = new BufferedReader(irdr);
Pattern crumbPattern = Pattern.compile(".*\"CrumbStore\":\\{\"crumb\":\"([^\"]+)\"\\}.*");
String line = null;
while (crumb == null && (line = rsv.readLine()) != null) {
Matcher matcher = crumbPattern.matcher(line);
if (matcher.matches())
crumb = matcher.group(1);
}
rsv.close();
System.out.println("Crumb is : "+crumb);
return crumb;
}
// This method extracts the cookies from response headers and passes the same con object to searchCrumb()
// method to extract the crumb and set the crumb value in finalCrumb global variable
private Map<String, List<String>> setCookies(String mainUrl) throws IOException {
// "https://finance.yahoo.com/quote/SPY";
Map<String, List<String>> map = new HashMap<String, List<String>>();
URL url = new URL(mainUrl);
URLConnection con = url.openConnection();
finalCrumb = searchCrumb(con);
for (Map.Entry<String, List<String>> entry : con.getHeaderFields().entrySet()) {
if (entry.getKey() == null || !entry.getKey().equals("Set-Cookie"))
continue;
for (String s : entry.getValue()) {
map.put(entry.getKey(), entry.getValue());
System.out.println(map);
}
}
return map;
}
public ArrayList<GregorianCalendar> getDates() {
return dates;
}
}
Have got much details regarding the finance API here.
Give a try!
A 401 error code means the user is unauthorised. Take a look again at YQL and if you are sure that everything you did is correct but the issue is still there then check out this library. This makes life easier in using Yahoo Finance API.
Related
The Java SDK docs don't cover launching a spot instance into a VPC with a Public IP: https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/tutorial-spot-adv-java.html.
How to do that?
Here's a SSSCE using aws-java-sdk-ec2-1.11.487:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import com.amazonaws.services.ec2.AmazonEC2;
import com.amazonaws.services.ec2.AmazonEC2ClientBuilder;
import com.amazonaws.services.ec2.model.CreateTagsRequest;
import com.amazonaws.services.ec2.model.InstanceNetworkInterfaceSpecification;
import com.amazonaws.services.ec2.model.InstanceType;
import com.amazonaws.services.ec2.model.LaunchSpecification;
import com.amazonaws.services.ec2.model.RequestSpotInstancesRequest;
import com.amazonaws.services.ec2.model.SpotInstanceRequest;
import com.amazonaws.services.ec2.model.Tag;
public class SpotLauncher
{
private static final int kInstances = 25;
private static final String kMaxPrice = "0.007";
private static final InstanceType kInstanceType = InstanceType.M3Medium;
private static final String kSubnet = "subnet-xxxx";
private static final String kAmi = "ami-xxxx";
private static final String kName = "spot";
private static final String kSecurityGroup2 = "sg-xxxx";
private static final String kSecurityGroup1 = "sg-yyyy";
public static void main(String[] args)
{
AmazonEC2 ec2 = AmazonEC2ClientBuilder.defaultClient();
RequestSpotInstancesRequest request = new RequestSpotInstancesRequest();
request.setSpotPrice(kMaxPrice); // max price we're willing to pay
request.setInstanceCount(kInstances);
LaunchSpecification launchSpecification = new LaunchSpecification();
launchSpecification.setImageId(kAmi);
launchSpecification.setInstanceType(kInstanceType);
launchSpecification.setKeyName("aws");
// security group IDs - don't add them, they're already added to the network spec
// launchSpecification.withAllSecurityGroups(new GroupIdentifier().withGroupId("sg-xxxx"), new GroupIdentifier().withGroupId("sg-yyyy"));
List<String> securityGroups = new ArrayList<String>();
securityGroups.add(kSecurityGroup1);
securityGroups.add(kSecurityGroup2);
InstanceNetworkInterfaceSpecification networkSpec = new InstanceNetworkInterfaceSpecification();
networkSpec.setDeviceIndex(0);
networkSpec.setSubnetId(kSubnet);
networkSpec.setGroups(securityGroups);
networkSpec.setAssociatePublicIpAddress(true);
List<InstanceNetworkInterfaceSpecification> nicWrapper = new ArrayList<InstanceNetworkInterfaceSpecification>();
nicWrapper.add(networkSpec);
// launchSpecification.setSubnetId("subnet-ccde4ce1"); // don't add this, it's already added to the network interface spec
launchSpecification.setNetworkInterfaces(nicWrapper);
// add the launch specifications to the request
request.setLaunchSpecification(launchSpecification);
// call the RequestSpotInstance API
ec2.requestSpotInstances(request);
while (!SetEc2Names(ec2))
{
Sleep(2000);
}
System.out.println("\nDONE.");
}
private static void Sleep(long aMillis)
{
try
{
Thread.sleep(aMillis);
}
catch (InterruptedException aEx)
{
aEx.printStackTrace();
}
}
private static boolean SetEc2Names(AmazonEC2 aEc2Client)
{
List<SpotInstanceRequest> requests = aEc2Client.describeSpotInstanceRequests().getSpotInstanceRequests();
Collections.sort(requests, GetCreatedDescComparator());
for (int i = 0; i < kInstances; i++)
{
SpotInstanceRequest request = requests.get(i);
if (request.getLaunchSpecification().getImageId().equals(kAmi))
{
System.out.println("request: " + request);
String instanceId = request.getInstanceId();
if (instanceId == null)
{
System.out.println("instance not launched yet, we don't have an id");
return false;
}
System.out.println("setting name for newly launched spot instance, id: " + instanceId);
AssignName(aEc2Client, request);
}
}
return true;
}
private static void AssignName(AmazonEC2 aEc2Client, SpotInstanceRequest aRequest)
{
String instanceId = aRequest.getInstanceId();
Tag tag = new Tag("Name", kName);
CreateTagsRequest tagRequest = new CreateTagsRequest();
List<String> instanceIds = new ArrayList<String>();
instanceIds.add(instanceId);
tagRequest.withResources(instanceIds);
List<Tag> tags = new ArrayList<Tag>();
tags.add(tag);
tagRequest.setTags(tags);
aEc2Client.createTags(tagRequest);
}
private static Comparator<SpotInstanceRequest> GetCreatedDescComparator()
{
return new Comparator<SpotInstanceRequest>()
{
#Override
public int compare(SpotInstanceRequest o1, SpotInstanceRequest o2)
{
return -1 * o1.getCreateTime().compareTo(o2.getCreateTime());
}
};
}
}
I have a program that creates a webgraph from text files. Every Time I run it I get the same message that says "Scanner Closed."
//constant final variables
public static final String PAGES_FILE = "pages.txt";
public static final String LINKS_FILE = "links.txt";
// webgraph object var
private WebGraph web;
// searchEngine constructor.
public SearchEngine() throws FileNotFoundException {
web = WebGraph.buildFromFiles(PAGES_FILE, LINKS_FILE);
}
Scanner Portion
try {
System.out.println("Loading WebGraph data...");
SearchEngine engine = new SearchEngine();
System.out.println("Success!");
Scanner scanner = new Scanner(System.in);
I have the scanner.close() right after the try block which contains all the possible user inputs. I have also attached an image of what should be happening once I run the program. Any ideas what could be going wrong? If any other code is needed I can provide that.Sample Program
Here is the image of what I am getting My Run
This is the code for the "buildFromFiles"
public static WebGraph buildFromFiles(String pagesFile, String linksFile)
throws IllegalArgumentException, FileNotFoundException {
WebGraph webGraph = new WebGraph();
File filePages = new File(pagesFile);
File fileLinks = new File(linksFile);
if (filePages.exists() && fileLinks.exists() && filePages.isFile() && fileLinks.isFile()) {
Scanner pageScanner = new Scanner(filePages);
while (pageScanner.hasNextLine()) {
String[] pageData = pageScanner.nextLine().split("\\s+");
String url = pageData[0];
ArrayList<String> keywords = new ArrayList<String>();
for (int i = 1; i < pageData.length; i++) {
keywords.add(pageData[i]);
}
webGraph.addPage(url, keywords);
}
pageScanner.close();
Scanner linkScanner = new Scanner(fileLinks);
while (linkScanner.hasNextLine()) {
String[] linkData = pageScanner.nextLine().split("\\s+");
webGraph.addLink(linkData[0], linkData[1]);
}
linkScanner.close();
} else {
throw new IllegalArgumentException();
}
return webGraph;
}
I'm storing Data in Map and Fetching the Field values now instead of Map I want to store data in Redis. I'm new to Redis and using below code to store in Redis :
public class CachingRedis {
private static HashMap<String, UserFields> Cache;
private static JedisPool pool = null;
private static final String redisHost = "localhost";
private static final Integer redisPort = 6379;
static Jedis jedis = null;
static User u;
public CachingRedis() {
pool = new JedisPool(redisHost, redisPort);
this.Cache = new HashMap<String, UserFields>();
}
public static void main(String[] args) throws ExecutionException {
CachingRedis gt = new CachingRedis();
gt.addSets();
}
private void addSets() {
InputStream in = ClassLoader.class.getResourceAsStream("/users.csv");
u = new User(in);
String[] consideredUserFields = { "Area","FirstName","LastName","Contact","Level"};
List<String[]> users = p.getUsers();
jedis = pool.getResource();
int count1 = 0;
String token = null;
String fieldName = null;
String fieldVal = null;
for (int i = 0; i < users.size(); i++) {
UserFields uFields = new UserFields();
String tmpId = Integer.toString(p.getUserId(i));
String[] tmpFields = Users.get(i);
for (int j = 0; j < tmpFields.length; j++) {
fieldName = consideredUsersFields[j];
fieldVal = tmpFields[j];
if (Cache != null && Cache.containsKey(tmpId)) {
uFields = Cache.get(tmpId);
uFields.setFieldKeyValues(fieldName, fieldVal);
Cache.put(tmpId, uFields);
**jedis.hsetnx( tmpId,fieldName,fieldVal );**
} else {
uFields.setFieldKeyValues(fieldName, fieldVal);
Cache.put(tmpId, pFields);
**jedis.hsetnx( tmpId,fieldName,fieldVal );**
}
}
}
} }
I'm getting the following error
Exception in thread "main" redis.clients.jedis.exceptions.JedisDataException: WRONGTYPE Operation against a key holding the wrong kind of value
at redis.clients.jedis.Protocol.processError(Protocol.java:117)
at redis.clients.jedis.Protocol.process(Protocol.java:142)
at redis.clients.jedis.Protocol.read(Protocol.java:196)
at redis.clients.jedis.Connection.readProtocolWithCheckingBroken(Connection.java:288)
at redis.clients.jedis.Connection.getIntegerReply(Connection.java:213)
at redis.clients.jedis.Jedis.lpush(Jedis.java:814)
at net.cintell.CachingRedis.addSets(CachingRedis.java:85)
at net.cintell.CachingRedis.main(CachingRedis.java:48)
Can anyone tell where I am doing wrong? I want to store the csv file into redis and fetch respective fields?
public class CachingRedis {
private static HashMap<String, UserFields> Cache;
private static JedisPool pool = null;
private static final String redisHost = "localhost";
private static final Integer redisPort = 6379;
static Jedis jedis = null;
static User u;
public CachingRedis() {
pool = new JedisPool(redisHost, redisPort);
this.Cache = new HashMap<String, UserFields>();
}
public static void main(String[] args) throws ExecutionException {
CachingRedis gt = new CachingRedis();
gt.addSets();
}
private void addSets() {
InputStream in = ClassLoader.class.getResourceAsStream("/users.csv");
u = new User(in);
String[] consideredUserFields = { "Area","FirstName","LastName","Contact","Level"};
List<String[]> users = p.getUsers();
jedis = pool.getResource();
int count1 = 0;
String token = null;
String fieldName = null;
String fieldVal = null;
for (int i = 0; i < users.size(); i++) {
UserFields uFields = new UserFields();
String tmpId = Integer.toString(p.getUserId(i));
String[] tmpFields = Users.get(i);
for (int j = 0; j < tmpFields.length; j++) {
fieldName = consideredUsersFields[j];
fieldVal = tmpFields[j];
if (Cache != null && Cache.containsKey(tmpId)) {
uFields = Cache.get(tmpId);
uFields.setFieldKeyValues(fieldName, fieldVal);
Cache.put(tmpId, uFields);
} else {
uFields.setFieldKeyValues(fieldName, fieldVal);
Cache.put(tmpId, pFields);
}
}
}
Map<String, String> Properties = new HashMap<String, String>();
for (Map.Entry<String, PersonaFields> entry : Cache.entrySet()) {
Properties.put("Id", entry.getKey());
Properties.put("Area", entry.getValue()
//rest of the fields
jedis.hmset("Users"+ entry.getKey(), Properties);
}
} }
I have loaded entire cache map into redis by loading each key value into other map so that I can retrieve based on same key value
from redis
Okay so I get an access token for Twitter each time I run my program...(It's tedious at the moment but I will find out how to make it a persistent store)... How do I go about using this access token so that when I search, I won't get a
"Rate limit exceeded. Clients may not make more than 150 requests per hour."
error?
It happens when I'm searching for the following: "https://api.twitter.com/1/users/show.json?screen_name=[screenName]"
Which is coded as :
BufferedReader ff = new BufferedReader( new InputStreamReader(ffUser.openConnection().getInputStream()));
In my code below:
public class UDC {
private static String term1;
private static String term2;
public static String PIN;
private static final String twitterSearch = "http://search.twitter.com/search.json?q=%23";
private static String rppPage = "&rpp=500&page=1";
private static final String ffGet = "https://api.twitter.com/1/users/show.json?screen_name=";
private static final String CONSUMER_KEY = "K7el7Fqu7UtcJv3A3ssOQ";
private static final String CONSUMER_SECRET = "w7ZX27ys58mafLYeivuA2POVe0gjhTIIUH26f2IM";
private static String entities = "&include_entities=true";
static Object[][] tableData = new Object[500][6];
static SearchResultC s = new SearchResultC();
static StringBuffer buff = new StringBuffer();
static StringBuffer buff1 = new StringBuffer();
public static void main (String args[]) throws Exception{
verifyURL v = new verifyURL();
Twitter twitter = new TwitterFactory().getInstance();
twitter.setOAuthConsumer(CONSUMER_KEY, CONSUMER_SECRET);
RequestToken requestToken = twitter.getOAuthRequestToken();
AccessToken accessToken = null; // = loadAccessToken(Integer.parseInt(args[0]));
//Twitter twitter = factory.getInstance);
//twitter.setOAuthConsumerKey(COMSUMER_KEY, COMSUMER_SECRET);
//twitter.setOAuthAccessToken(accessToken);
v.valURLText.setText(requestToken.getAuthorizationURL());
v.vFrame.setVisible(true);
int p = 0;
do {
//nothing
} while (v.vFrame.isVisible());
try {
if (PIN.length() > 0) {
accessToken = twitter.getOAuthAccessToken(requestToken, PIN);
} else {
accessToken = twitter.getOAuthAccessToken();
}
} catch (TwitterException te) {
if(401 == te.getStatusCode()) {
showErrorPane("Unable to get access code", "Error");
p = 1;
} else {
te.printStackTrace();
}
}
//storeAccessToken(twitter.verifyCredentials().getId(), accessToken);
if (p == 0) {
initComponents();
UDTFrame.setVisible(true);
} else {
System.exit(0);
}
}
#SuppressWarnings({ "static-access"})
private static void searchButtonMouseClicked(String t1, String t2) throws IOException {
if(t1.equals("") || t2.equals("") || t1.equals(t2))
{
showErrorPane("Invalid Search Terms", "Search Error");
}
else
{
s.getInitComponents();
clicked(t1, 0);
clicked(t2, 3);
s.SRTFrame.setVisible(true);
s.sTerm1Field.setText(t1);
s.sTerm2Field.setText(t2);
}
}
#SuppressWarnings("static-access")
public static void clicked(String term, int t){
UDTFrame.setVisible(false);
float follower;
float friends;
float ffRatio;
float DUA;
int statuses;
int day;
int year;
String month;
try {
URL searchURL1 = new URL (twitterSearch + term + rppPage);
//String searchURL = new String (twitterSearch + term + rppPage);
BufferedReader br = new BufferedReader( new InputStreamReader(searchURL1.openConnection().getInputStream()));
//OAuthRequest request = new OAuthRequest(Verb.POST, searchURL);
int c;
while ((c=br.read()) != -1) {
buff.append((char)c);
}
br.close();
/*******************************************************************************************/
/*******************************************************************************************/
/******************************** follower/friend ratio ************************************/
/*******************************************************************************************/
/*******************************************************************************************/
JSONObject js = new JSONObject(buff.toString());
JSONArray tweets = js.getJSONArray("results");
JSONObject tweet = new JSONObject();
for(int i=0; i < tweets.length(); i++) {
tweet = tweets.getJSONObject(i);
//System.out.println(tweet);
//user[i] = tweet.getString("from_user_name");
//System.out.println(tweet.getString("from_user_name"));
//System.out.println(user[i]);
String userName = tweet.getString("from_user");
//URL ffUser = new URL(ffGet + user[i] + entities);
URL ffUser = new URL(ffGet + userName + entities);
String ffUser1 = new String(ffGet + userName + entities);
BufferedReader ff = new BufferedReader( new InputStreamReader(ffUser.openConnection().getInputStream()));
OAuthRequest request = new OAuthRequest(Verb.POST, ffUser1);
int d, e = 0;
while((d = ff.read()) != -1) {
buff1.append((char)d);
e++;
}
ff.close();
JSONObject js1 = new JSONObject(buff1.toString());
//System.out.println(js1);
//JSONArray userData = new JSONArray(buff1.toString());
//JSONObject userData1;
//for(int j = 0; j < js1.length(); i++){
//userData1 = userData.getJSONObject(j);
follower = js1.getInt("followers_count");
friends = js1.getInt("friends_count");
ffRatio = friends/follower;
String createdDate = js1.getString("created_at");
statuses = js1.getInt("statuses_count");
String nameData = js1.getString("name");
String gen = gender(nameData);
//}
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I'm completely new to this OAuth and Access Tokens and all so any help will be much appreciated.
With
OAuthRequest request = new OAuthRequest(Verb.POST, ffUser1);
you are doing an unauthenticated request using the Scribe library (you never instantiated an OAuthService object which would have to be used to sign this request). So when you do this too often Twitter denies these requests.
So your problem here does indeed come from mixing Twitter4J and Scribe.
I wrote a simple java application, I have a problem please help me;
I have a file (JUST EXAMPLE):
1.TXT
-------
SET MRED:NAME=MRED:0,MREDID=60;
SET BCT:NAME=BCT:0,NEPE=DCS,T2=5,DK0=KOR;
CREATE LCD:NAME=LCD:0;
-------
and this is my source code
import java.io.IOException;
import java.io.*;
import java.util.StringTokenizer;
class test1 {
private final int FLUSH_LIMIT = 1024 * 1024;
private StringBuilder outputBuffer = new StringBuilder(
FLUSH_LIMIT + 1024);
public static void main(String[] args) throws IOException {
test1 p=new test1();
String fileName = "i:\\1\\1.txt";
File file = new File(fileName);
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
StringTokenizer st = new StringTokenizer(line, ";|,");
while (st.hasMoreTokens()) {
String token = st.nextToken();
p.processToken(token);
}
}
p.flushOutputBuffer();
}
private void processToken(String token) {
if (token.startsWith("MREDID=")) {
String value = getTokenValue(token,"=");
outputBuffer.append("MREDID:").append(value).append("\n");
} else if (token.startsWith("DK0=")) {
String value = getTokenValue(token,"=");
outputBuffer.append("DK0=:").append(value).append("\n");
} else if (token.startsWith("NEPE=")) {
String value = getTokenValue(token,"=");
outputBuffer.append("NEPE:").append(value).append("\n");
}
if (outputBuffer.length() > FLUSH_LIMIT) {
flushOutputBuffer();
}
}
private String getTokenValue(String token,String find) {
int start = token.indexOf(find) + 1;
int end = token.length();
String value = token.substring(start, end);
return value;
}
private void flushOutputBuffer() {
System.out.print(outputBuffer);
outputBuffer = new StringBuilder(FLUSH_LIMIT + 1024);
}
}
I want this output :
MREDID:60
DK0=:KOR
NEPE:DCS
But this application show me this :
MREDID:60
NEPE:DCS
DK0=:KOR
please tell me how can i handle this , because of that DK0 must be at first and this is just a sample ; my real application has 14000 lines
Thanks ...
Instead of outputting the value when you read it, put it in a hashmap. Once you've read your entire file, output in the order you want by getting the values from the hashmap.
Use a HashTable to store the values and print from it in the desired order after parsing all tokens.
//initialize hash table
HashTable ht = new HashTable();
//instead of outputBuffer.append, put the values in to the table like
ht.put("NEPE", value);
ht.put("DK0", value); //etc
//print the values after the while loop
System.out.println("MREDID:" + ht.get("MREDID"));
System.out.println("DK0:" + ht.get("DK0"));
System.out.println("NEPE:" + ht.get("NEPE"));
Create a class, something like
class data {
private int mredid;
private String nepe;
private String dk0;
public void setMredid(int mredid) {
this.mredid = mredid;
}
public void setNepe(String nepe) {
this.nepe = nepe;
}
public void setDk0(String dk0) {
this.dk0 = dk0;
}
public String toString() {
String ret = "MREDID:" + mredid + "\n";
ret = ret + "DK0=:" + dk0 + "\n";
ret = ret + "NEPE:" + nepe + "\n";
}
Then change processToken to
private void processToken(String token) {
Data data = new Data();
if (token.startsWith("MREDID=")) {
String value = getTokenValue(token,"=");
data.setMredid(Integer.parseInt(value));
} else if (token.startsWith("DK0=")) {
String value = getTokenValue(token,"=");
data.setDk0(value);
} else if (token.startsWith("NEPE=")) {
String value = getTokenValue(token,"=");
data.setNepe(value);
}
outputBuffer.append(data.toString());
if (outputBuffer.length() > FLUSH_LIMIT) {
flushOutputBuffer();
}
}