I am following this Youtube tutorial, but while he gets ALL the headlines from CNN RSS, I only get 1 headline. Why is this so?
my code (same as the one in the tutorial as far as I can see)
import java.net.MalformedURLException;
import java.net.URL;
import java.io.*;
public class ReadRSS {
public static void main(String[] args) {
System.out.println(readRSSFeed("http://rss.cnn.com/rss/edition.rss"));
}
public static String readRSSFeed(String urlAddress){
try{
URL rssUrl = new URL (urlAddress);
BufferedReader in = new BufferedReader(new InputStreamReader(rssUrl.openStream()));
String sourceCode = "";
String line;
while((line=in.readLine())!=null){
if(line.contains("<title>")){
System.out.println(line);
int firstPos = line.indexOf("<title>");
String temp = line.substring(firstPos);
temp=temp.replace("<title>","");
int lastPos = temp.indexOf("</title>");
temp = temp.substring(0,lastPos);
sourceCode +=temp+ "\n" ;
}
}
in.close();
return sourceCode;
} catch (MalformedURLException ue){
System.out.println("Malformed URL");
} catch (IOException ioe){
System.out.println("Something went wrong reading the contents");
}
return null;
}
}
CNN's feed format has changed since he made that Youtube video. The code makes the assumption that there is one title tag per line, when actually there are multiple. Something like this should work now:
while ((line = in.readLine()) != null) {
int titleEndIndex = 0;
int titleStartIndex = 0;
while (titleStartIndex >= 0) {
titleStartIndex = line.indexOf("<title>", titleEndIndex);
if (titleStartIndex >= 0) {
titleEndIndex = line.indexOf("</title>", titleStartIndex);
sourceCode += line.substring(titleStartIndex + "<title>".length(), titleEndIndex) + "\n";
}
}
}
Related
I declared a global vector, and I'm trying to access it globally, but it throws an error.
It says cannot find symbol XArray or YArray.
The code I'm using (I've cut some of it out that I thought was not necessary):
public class Main {
public static void main(String[] args) {
String csvFile = "/Users/hherzberg/Desktop/testData.csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
ArrayList<Point3D> myPoints = new ArrayList<Point3D>();
ArrayList<Double> XArray = new ArrayList<Double>();
ArrayList<Double> YArray = new ArrayList<Double>();
try {
int xcount=0;
int ycount=0;
double multiplied=0;
br = new BufferedReader(new FileReader(csvFile));
br.readLine();
while ((line = br.readLine()) != null) {
// use comma as separator
String[] number = line.split(cvsSplitBy);
double x = Double.parseDouble(number[0]);
double y = Double.parseDouble(number[1]);
XArray.add(x);
YArray.add(y);
Point3D p = new Point3D(x, y);
myPoints.add(p);
xcount+=1;
ycount+=1;
System.out.println(p);
}
for (int i=0; i<myPoints.size();i++)
{
multiplied+=Double.parseDouble(XArray(i))*Double.parseDouble(YArray(i+1));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
Some help with this would be greatly appreciated.
Use below import at first line and it should work
import java.io.*;
import java.util.*;
This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
Closed 6 years ago.
The purpose of the class below is to get text from different articles of different news websites. The version below is designed for Android, but it throws a NetworkOnMainThread Exception when run. When I used an earlier version of this class, made specifically to run on a computer, it worked fine, but I'm not really sure how network I/O works on Android. I've seen some other answers to questions about this topic, but I don't understand why in Android the program throws an exception but on a desktop it works fine. Can anyone explain?
package com.example.user.helloworld;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
public class ArticleReceiver {
private ArrayList<Article> newsArticles = new ArrayList<>();
private ArrayList<String> newsLinks = new ArrayList<>();
public ArticleReceiver(int numArticles, String link) {
if (numArticles != 0) {
receiveNewsArticles(numArticles, link);
}else{
System.out.println("ERROR: numArticles request for " + link + " cannot equal 0.");
}
}
private void receiveNewsArticles(int numArticles, String urlAddress) {
URL rssUrl = null;
// if connected to Internet
if (true){//isInternetAvailable()) {
try {
// gather links
rssUrl = new URL(urlAddress);
BufferedReader in = new BufferedReader(new InputStreamReader(rssUrl.openStream()));
String line;
// fix bbc trash urls
if (urlAddress.equals(Main.BBC_URL)) {
numArticles++;
}
while ((line = in.readLine()) != null && newsLinks.size() <= numArticles) {
if (line.contains("<link>")) {
// find links through tags
int firstPos = line.indexOf("<link>");
String temp = line.substring(firstPos);
temp = temp.replace("<link>", "");
int lastPos = temp.indexOf("</link>");
temp = temp.substring(0, lastPos);
newsLinks.add(temp);
}
}
in.close();
// test if there are links and if there is remove first
// unnecessary
// link
if (!newsLinks.isEmpty()) {
if (urlAddress.equals(Main.BBC_URL)) {
newsLinks.remove(0);
newsLinks.remove(0);
}else if(urlAddress.equals(Main.CNN_URL) || urlAddress.equals(Main.FOX_URL) || urlAddress.equals(Main.ESPN_URL)){
newsLinks.remove(0);
}
} else {
System.out.println("ERROR: No Found Articles. Check If You Have Wifi.");
}
// gather articles from HTML "section" or "p" tag of article using Jsoup
for (String newsLink : newsLinks) {
// get webpage
Document doc = Jsoup.connect(newsLink).get();
// get article from different websites
String article = null;
if (urlAddress.equals(Main.FOX_URL)) {
Elements element = doc.select("p");
article = element.text();
} else if (urlAddress.equals(Main.CNN_URL)) {
Elements element = doc.select("section");
article = element.text();
} else if (urlAddress.equals(Main.BBC_URL)) {
Elements element = doc.select("p");
article = element.text();
}else if(urlAddress.equals(Main.ESPN_URL)){
Elements element = doc.select("p");
article = element.text();
}
newsArticles.add(new Article(article, Main.SUMMARY_SENTENCES));
}
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.out.println("ERROR: No internet connection established.");
return;
}
}
public ArrayList<Article> getArticles() {
return newsArticles;
}
public Article getArticle(int i) {
if (newsArticles.size() <= i) {
return null;
} else {
return newsArticles.get(i);
}
}
//The method below does not recognize the "getSystemService" method, and when the method is no longer present there is a NetworkOnMainThreadException
private boolean isInternetAvailable() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
}
You need to execute web service connections asynchronous.
What I use in my projects is have a class ApiConnection and with interface get response. Example:
Apiconnection class
public class APIConnection extends AsyncTask<Object, String, Void> {
private final String TAG = "API-CONNECTION";
private StringBuilder sbuilder;
private JSONObject json;
private APIConnectionInterface mInterface;
protected int httpResponseCode = 0;
private String entity = null, url;
private APIConnectionType mmode;
private boolean DEBUG = BuildConfig.DEBUG;
private String[][] headers;
/**
Constructor For APIConnection
*/
public APIConnection(APIConnectionInterface thisdelegate, APIConnectionType mode, String murl, String entity) {
this.mInterface = thisdelegate;
this.mmode = mode;
this.url = murl;
this.entity = entity;
initHeaders();
}
private void initHeaders(){
headers = new String[][]{
{"token", "MY_TOKEN"},
{"Content-Type", "application/json;charset=utf-8"},
{"user-agent", "android"},
{"Accept-Language", "es"}
};
}
#Override
protected Void doInBackground(Object... params) {
BufferedReader buffer = null;
InputStreamReader in = null;
OutputStream os = null;
int timeoutConnection = 30000, timeoutSocket = 20000;
try{
sbuilder = new StringBuilder();
url = convertURL(url);
if (entity==null)entity="{}";
URL u = new URL(url);
HttpURLConnection conn;
if (url.startsWith("https://"))
conn = (HttpsURLConnection) u.openConnection();
else
conn = (HttpURLConnection) u.openConnection();
conn.setReadTimeout(timeoutConnection);
conn.setConnectTimeout(timeoutSocket);
for (String[] arr : headers){ conn.addRequestProperty(arr[0], arr[1]); }
/*GET*/if (mmode == APIConnectionType.GET) {
conn.setDoInput(true);
conn.setRequestMethod(mmode.toString());
httpResponseCode = conn.getResponseCode();
in = new InputStreamReader(
httpResponseCode == HttpURLConnection.HTTP_OK ? conn.getInputStream() : conn.getErrorStream(),"UTF-8");
/*OTHER*/} else if (mmode == APIConnectionType.POST || mmode == APIConnectionType.PUT ||
mmode == APIConnectionType.PATCH || mmode == APIConnectionType.DELETE) {
conn.setRequestMethod(mmode.toString());
conn.setDoOutput(true);
byte[] outputInBytes = entity.getBytes("UTF-8");
os = conn.getOutputStream();
os.write( outputInBytes );
httpResponseCode = conn.getResponseCode();
in = new InputStreamReader(
httpResponseCode == HttpURLConnection.HTTP_OK ? conn.getInputStream() : conn.getErrorStream(), "UTF-8");
}
if (in!=null){
buffer=new BufferedReader(in);
String line;
while ((line = buffer.readLine()) != null) {
sbuilder.append(line);
}
}else {
sbuilder.append("");
}
}
catch(IOException e) {
if (DEBUG)Log.d(TAG, "onBackground Exception " + e.getMessage());
sbuilder= new StringBuilder();
httpResponseCode = 0;
cancel(true);
return null;
} finally {
if (buffer != null) {
try {
buffer.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
if (os!=null){
try {
os.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
#Override
protected void onPostExecute(Void result){
try{
if (DEBUG) timelapse_e = System.currentTimeMillis();
if (sbuilder != null) {
json = new JSONObject(sbuilder.toString());
}
if (sbuilder != null){
sbuilder.setLength(0);
sbuilder.trimToSize();
}
sbuilder = null;
GoRunning();
hideDialog();
}
catch(RuntimeException e) {
if (DEBUG)Log.d(TAG, "PostExecute RuntimeException " + e.getMessage());
cancel(true);
}
catch(Exception e) {
if (DEBUG)Log.d(TAG, "PostExecute Exception " + e.getMessage());
cancel(true);
}
}
#Override protected void onCancelled() {
if (mInterface != null) mInterface.onCancelled(APIConnection.this);
super.onCancelled();
}
#Override protected void onPreExecute() {
super.onPreExecute();
if (DEBUG) timelapse_s = System.currentTimeMillis();
if (mInterface != null) mInterface.onStartLoading(APIConnection.this);
}
public void GoRunning(){
if (mInterface != null) try {
mInterface.onDataArrival(APIConnection.this, json, httpResponseCode);
} catch (JSONException e) {
onCancelled();
e.printStackTrace();
}
}
/**
* Hide Dialog (Progress dialog) if is showing and activity NOT Finishing
*/
private void hideDialog() {
if (mInterface != null) mInterface.onFinishedLoading(APIConnection.this);
}
/** <b>convertURL(String str);</b><br/>
* replaces any special characters to <b>%??</b><br/>
* Replacements actived:<br/>
* "{Space}" ==> "%20"
* #param str URL to encode
* #return url encoded
*/
public static String convertURL(String str) {
return str.trim().replace(" ", "%20");
// .replace("&", "%26")
// .replace(",", "%2c").replace("(", "%28").replace(")", "%29")
// .replace("!", "%21").replace("=", "%3D").replace("<", "%3C")
// .replace(">", "%3E").replace("#", "%23").replace("$", "%24")
// .replace("'", "%27").replace("*", "%2A").replace("-", "%2D")
// .replace(".", "%2E").replace("/", "%2F").replace(":", "%3A")
// .replace(";", "%3B").replace("?", "%3F").replace("#", "%40")
// .replace("[", "%5B").replace("\\", "%5C").replace("]", "%5D")
// .replace("_", "%5F").replace("`", "%60").replace("{", "%7B")
// .replace("|", "%7C").replace("}", "%7D"));
}
public interface APIConnectionInterface {
void onDataArrival(APIConnection apiConnection, JSONObject json, int httpResponseCode) throws JSONException;
void onStartLoading(APIConnection apiConnection);
void onFinishedLoading(APIConnection apiConnection);
void onCancelled(APIConnection apiConnection);
}
public enum APIConnectionType {
GET("GET"),
POST("POST"),
PUT("PUT"),
PATCH("PATCH"),
DELETE("DELETE");
private String methodName;
APIConnectionType(String methodName){this.methodName = methodName;}
#Override public String toString() {return methodName;}
}
}
And then from any Activity or Fragment I can call the web service async
like this:
new APIConnection(new APIConnection.APIConnectionInterface() {
#Override public void onDataArrival(APIConnection apiConnection, JSONObject json, int httpResponseCode) {
try {
if (isHttpResponseOk(httpResponseCode, json)){//200 or 201
JSONObject obj = json.getJSONObject("results");
// do things with json
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override public void onStartLoading(APIConnection apiConnection) {showProgressDialog();}
#Override public void onFinishedLoading(APIConnection apiConnection) {hideProgressDialog();}
#Override public void onCancelled(APIConnection apiConnection) {hideProgressDialog();}
}, APIConnection.APIConnectionType.GET, MyApp.API_URL + "/master_data/", null).execute();
The only thing you need is to adapt the response to other object you need.
I hope that helps
I'm trying to write a .dat file to an ArrayList. The file contains lines formatted like this : #name#,#number#.
Scanner s = new Scanner(new File("file.dat"));
while(s.hasNext()){
String string = s.next();
names.add(string.split(",")[0];
numbers.add(Integer.parseInt(string.split(",")[1];
}
If I check if it runs with printing, all I get is the first line.
With standard Java libraries (full code example):
BufferedReader in = null;
List<String> myList = new ArrayList<String>();
try {
in = new BufferedReader(new FileReader("myfile.txt"));
String str;
while ((str = in.readLine()) != null) {
myList.add(str);
//Or split your read string here as you wish.
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null) {
in.close();
}
}
With other common libraries:
A one-liner with commons-io:
List<String> lines = FileUtils.readLines(new File("/path/to/file.txt"), "utf-8");
The same with guava:
List<String> lines =
Files.readLines(new File("/path/to/file.txt"), Charset.forName("utf-8"));
Then you can iterate over the read lines and split each String to your desired ArrayLists.
Instead of using a Scanner, use a BufferedReader. The BufferedReader provides a method to read one line at a time. Using this, you can process every line individually by splitting them (line.split(",")) , stripping the trailing hashes, then pushing them into your ArrayLists.
This is how I read a file and turn it into a arraylist
public List<String> readFile(File file){
try{
List<String> out = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
String line;
while((line = reader.readLine()) != null){
if(line != null){
out.add(line);
}
}
reader.close();
return out;
}
catch(IOException e){
}
return null;
}
Hope it helps.
May be this is lengthy way but works:
text file:
susheel,1134234
testing,1342134
testing2,123455
Main class:
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
public class Equal {
public static void main(String[] args) {
List<Pojo> data= new ArrayList<Pojo>();
String currentLine;
try {
BufferedReader br = new BufferedReader(new FileReader("E:\\test.dat"));
while ((currentLine = br.readLine()) != null) {
String[] arr = currentLine.split(",");
Pojo pojo = new Pojo();
pojo.setName(arr[0]);
pojo.setNumber(Long.parseLong(arr[1]));
data.add(pojo);
}
for(Pojo i : data){
System.out.print(i.getName()+" "+i.getNumber()+"\n");
}
} catch (Exception e) {
System.out.print(e.getMessage());
}
}
}
POJO class:
public class Pojo {
String name;
long number;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public long getNumber() {
return number;
}
public void setNumber(long number) {
this.number = number;
}
}
my text
is like that
SEHiR;iL;iLCE;Tip;22356
S SI n;ISTA;ANK;A:S;22356
K K n;IS:TA;BB;B:S;22356
A A b;IS.TA;CC;DK;22356
G S b;ISTA;DD;O:P;22356
I want to change TIP column. I want to put "." instead of ":" for only Tıp column which include A:S,B:S etc.. And I want to write line before changing and after changing to csv. How can I do that? I write something but it has problem at
if(eD.tip.contains(":")) part because it dont continue to hS.Add(eD)
endeks.put("", hS); ı don’t want use “” string.
I do not have to use HasMap I could not write output what I want..
ı expected this output
S SI n;ISTA;ANK;A:S;22356
S SI n;ISTA;ANK;A.S;22356
K K n;IS:TA;BB;B:S;22356
K K n;IS:TA;BB;B.S;22356
G S b;ISTA;DD;O:P;22356
G S b;ISTA;DD;O.P;22356
public class MaliyeVknmDegil {
static class EndeksDegeri {
String sirket ;
String sehir;
String ilce;
String tip;
int numara;
}
static HashMap<String,HashSet<EndeksDegeri>> endeks = new HashMap<String, HashSet<EndeksDegeri>>();
static PrintWriter pW;
static EndeksDegeri eD = new EndeksDegeri();
static String satır;
private static PrintWriter pW2;
public static void main(String[] args) {
FileInputStream fIS;
FileOutputStream fOS;
try {
fIS = new FileInputStream("C:\\deneme\\DENEME.csv");
Reader r = new InputStreamReader(fIS, "UTF-8");
BufferedReader bR = new BufferedReader(r);
fOS = new FileOutputStream("c:\\yazdirilan\\deneme.csv");
Writer w = new OutputStreamWriter(fOS, "UTF-8");
pW2 = (new PrintWriter(w));
String satır;
String[] eleman;
while ((satır = bR.readLine()) != null) {
eleman = satır.split(";");
if(satır.contains(":")){
pW2.write(satır);
}
HashSet<EndeksDegeri> hS = new HashSet<EndeksDegeri>();
for (int i = 0; i < eleman.length; i++) {
// alteleman=eleman[i].split(" ");
EndeksDegeri eD = new EndeksDegeri();
eD.sirket = eleman[0];
eD.sehir = eleman[1];
eD.ilce = eleman[2];
if(eD.tip.contains(":")){
eD.tip.replaceAll(":", ".");
eD.tip = eleman[3];
}
eD.numara = Integer.parseInt(eleman[4]);
hS.add(eD);
}
endeks.put("", hS);
}
bR.close();
// yazdir
HashSet<EndeksDegeri> hS;
for (String s : endeks.keySet()) {
hS = endeks.get(s);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
}
}// main end
}// clas end
package stackoverflow;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.Writer;
public class TipChange {
private static String inputPath = "input.csv";
private static String outputPath = "output.csv";
private static BufferedReader bufferedReader;
private static PrintWriter printWriter;
public static void main(String[] args) {
try {
FileInputStream inputStream = new FileInputStream(inputPath);
Reader reader = new InputStreamReader(inputStream, "UTF-8");
bufferedReader = new BufferedReader(reader);
FileOutputStream outputStream = new FileOutputStream(outputPath);
Writer writer = new OutputStreamWriter(outputStream, "UTF-8");
printWriter = new PrintWriter(writer);
String line;
while ((line = bufferedReader.readLine()) != null) {
EndeksDegeri eD = lineToClass(line);
if (shouldOutput(eD)) {
printWriter.append(classToLine(eD, true));
printWriter.append(classToLine(eD, false));
}
}
} catch (IOException e) {
e.printStackTrace();
}
finally {
try {
bufferedReader.close();
printWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static boolean shouldOutput(EndeksDegeri eD) {
if (!eD.tip.contains(":")) {
return false;
}
return true;
}
private static String classToLine(EndeksDegeri eD, boolean original) {
if (!original) {
eD.tip = eD.tip.replace(":", ".");
}
return eD.sirket.concat(";")
.concat(eD.sehir).concat(";")
.concat(eD.ilce).concat(";")
.concat(eD.tip).concat(";")
.concat(String.valueOf(eD.numara)
.concat("\r\n"));
}
private static EndeksDegeri lineToClass(String line) {
String[] element = line.split(";");
EndeksDegeri endeksDegeri = new EndeksDegeri();
endeksDegeri.sirket = element[0];
endeksDegeri.sehir = element[1];
endeksDegeri.ilce = element[2];
endeksDegeri.tip = element[3];
endeksDegeri.numara = Integer.valueOf(element[4]);
return endeksDegeri;
}
private static class EndeksDegeri {
String sirket ;
String sehir;
String ilce;
String tip;
int numara;
}
}
Sample input:
SSI;ISTA;ANK;A:S;22356
KK;IS:TA;BB;B:S;22356
AA;IS.TA;CC;DK;22356
GS;ISTA;DD;O:P;22356
Generated Output:
SSI;ISTA;ANK;A:S;22356
SSI;ISTA;ANK;A.S;22356
KK;IS:TA;BB;B:S;22356
KK;IS:TA;BB;B.S;22356
GS;ISTA;DD;O:P;22356
GS;ISTA;DD;O.P;22356
Your code will produce a NullPointerException in the line: if(eD.tip.contains(":")){
That is because when a new EndeksDegeri instance is created all its fields are null you cannot call contains() on a null string.
Check the example code below (It writes to the console but it should get you going)
static class EndeksDegeri {
String sirket;
String sehir;
String ilce;
String tip;
int numara;
// I have added this method for convenience to write to the output
public String toString() {
return sirket + ":" + sehir + ":" + ilce + ":" + tip + ":" + numara;
}
}
while ((satir = bR.readLine()) != null) {
eleman = satir.split(";");
boolean found = false;
EndeksDegeri eD = new EndeksDegeri();
// first set all fields to not get exception
eD.sirket = eleman[0];
eD.sehir = eleman[1];
eD.ilce = eleman[2];
eD.tip = eleman[3];
eD.numara = Integer.parseInt(eleman[4]);
// check if the line contains ":"
if (eD.tip.contains(":")) {
// If yes, write the original line first
System.out.println(eD.toString());
// Change the record
eD.tip = eD.tip.replaceAll(":", ".");
found = true;
}
if (found) {
// write the corrected line now
System.out.println(eD.toString());
}
}
// Will print only the lines with ":" and its correct version
SSI:ISTA:ANK:A:S:22356
SSI:ISTA:ANK:A.S:22356
KK:IS:TA:BB:B:S:22356
KK:IS:TA:BB:B.S:22356
GS:ISTA:DD:O:P:22356
GS:ISTA:DD:O.P:22356
I work at a printing company that has many programs in COBOL and I have been tasked to
convert the COBOL programs into JAVA programs. I've run into a snag in the one conversion. I need to take a file that each line is a record and on each line the data is blocked.
Example of a line is
60000003448595072410013 FFFFFFFFFFV 80 0001438001000014530020120808060134
I need to sort data by a 5 digit number at the 19-23 characters and then by the very first character on a line.
BufferedReader input;
BufferedWriter output;
String[] sort, sorted, style, accountNumber, customerNumber;
String holder;
int lineCount;
int lineCounter() {
int result = 0;
boolean eof = false;
try {
FileReader inputFile = new FileReader("C:\\Users\\cbook\\Desktop\\Chemical\\"
+ "LB26529.fil");
input = new BufferedReader(inputFile);
while (!eof) {
holder = input.readLine();
if (holder == null) {
eof = true;
} else {
result++;
}
}
} catch (IOException e) {
System.out.println("Error - " + e.toString());
}
return result;
}
chemSort(){
lineCount = this.lineCounter();
sort = new String[lineCount];
sorted = new String[lineCount];
style = new String[lineCount];
accountNumber = new String[lineCount];
customerNumber = new String[lineCount];
try {
FileReader inputFile = new FileReader("C:\\Users\\cbook\\Desktop\\Chemical\\"
+ "LB26529.fil");
input = new BufferedReader(inputFile);
for (int i = 0; i < (lineCount + 1); i++) {
holder = input.readLine();
if (holder != null) {
sort[i] = holder;
style[i] = sort[i].substring(0, 1);
customerNumber[i] = sort[i].substring(252, 257);
}
}
} catch (IOException e) {
System.out.println("Error - " + e.toString());
}
}
This what I have so far and I'm not really sure where to go from here or even if this is the correct way
to go about sorting the file. After the file is sorted it will be stored into another file and processed
again with another program for it to be ready for printing.
List<String> linesAsList = new ArrayList<String>();
String line=null;
while(null!=(line=reader.readLine())) linesAsList.add(line);
Collections.sort(linesAsList, new Comparator<String>() {
public int compare(String o1,String o2){
return (o1.substring(18,23)+o1.substring(0,1)).compareTo(o2.substring(18,23)+o2.substring(0,1));
}});
for (String line:linesAsList) System.out.println(line); // or whatever output stream you want
This phone's autocorrect is messing up my answer
Read the file into an ArrayList (instead of an array). Use the following methods:
// to declare the arraylist
ArrayList<String> lines = new ArrayList<String>();
// to add a new line to it (within your reading-lines loop)
lines.add(input.readLine());
Then, sort it using a custom Comparator:
Collections.sort(lines, new Comparator<String>() {
public int compare(String a, String b) {
String a5 = theFiveNumbersOf(a);
String b5 = theFiveNumbersOf(b);
int firstComparison = a5.compareTo(b5);
if (firstComparison != 0) { return firstComparison; }
String a1 = theDigitOf(a);
String b1 = theDigitOf(b);
return a1.compareTo(b1);
}
});
(It is unclear what 5 digits or what digit you want to compare; I've left them as functions for you to fill in).
Finally, write it to the output file:
BufferedWriter ow = new BufferedWriter(new FileOutputStream("filename.extension"));
for (String line : lines) {
ow.println(line);
}
ow.close();
(adding imports and try/catch as needed)
This code will sort a file based on mainframe sort parameters.
You pass 3 parameters to the main method of the Sort class.
The input file path.
The output file path.
The sort parameters in mainframe sort format. In your case, this string would be 19,5,CH,A,1,1,CH,A
This first class, the SortParameter class, holds instances of the sort parameters. There's one instance for every group of 4 parameters in the sort parameters string. This class is a basic getter / setter class, except for the getDifference method. The getDifference method brings some of the sort comparator code into the SortParameter class to simplify the comparator code in the Sort class.
public class SortParameter {
protected int fieldStartByte;
protected int fieldLength;
protected String fieldType;
protected String sortDirection;
public SortParameter(int fieldStartByte, int fieldLength, String fieldType,
String sortDirection) {
this.fieldStartByte = fieldStartByte;
this.fieldLength = fieldLength;
this.fieldType = fieldType;
this.sortDirection = sortDirection;
}
public int getFieldStartPosition() {
return fieldStartByte - 1;
}
public int getFieldEndPosition() {
return getFieldStartPosition() + fieldLength;
}
public String getFieldType() {
return fieldType;
}
public String getSortDirection() {
return sortDirection;
}
public int getDifference(String a, String b) {
int difference = 0;
if (getFieldType().equals("CH")) {
String as = a.substring(getFieldStartPosition(),
getFieldEndPosition());
String bs = b.substring(getFieldStartPosition(),
getFieldEndPosition());
difference = as.compareTo(bs);
if (getSortDirection().equals("D")) {
difference = -difference;
}
}
return difference;
}
}
The Sort class contains the code to read the input file, sort the input file, and write the output file. This class could probably use some more error checking.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Sort implements Runnable {
protected List<String> lines;
protected String inputFilePath;
protected String outputFilePath;
protected String sortParameters;
public Sort(String inputFilePath, String outputFilePath,
String sortParameters) {
this.inputFilePath = inputFilePath;
this.outputFilePath = outputFilePath;
this.sortParameters = sortParameters;
}
#Override
public void run() {
List<SortParameter> parameters = parseParameters(sortParameters);
lines = read(inputFilePath);
lines = sort(lines, parameters);
write(outputFilePath, lines);
}
protected List<SortParameter> parseParameters(String sortParameters) {
List<SortParameter> parameters = new ArrayList<SortParameter>();
String[] field = sortParameters.split(",");
for (int i = 0; i < field.length; i += 4) {
SortParameter parameter = new SortParameter(
Integer.parseInt(field[i]), Integer.parseInt(field[i + 1]),
field[i + 2], field[i + 3]);
parameters.add(parameter);
}
return parameters;
}
protected List<String> sort(List<String> lines,
final List<SortParameter> parameters) {
Collections.sort(lines, new Comparator<String>() {
#Override
public int compare(String a, String b) {
for (SortParameter parameter : parameters) {
int difference = parameter.getDifference(a, b);
if (difference != 0) {
return difference;
}
}
return 0;
}
});
return lines;
}
protected List<String> read(String filePath) {
List<String> lines = new ArrayList<String>();
BufferedReader reader = null;
try {
String line;
reader = new BufferedReader(new FileReader(filePath));
while ((line = reader.readLine()) != null) {
lines.add(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return lines;
}
protected void write(String filePath, List<String> lines) {
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new FileWriter(filePath));
for (String line : lines) {
writer.write(line);
writer.newLine();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (writer != null) {
writer.flush();
writer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
if (args.length < 3) {
System.err.println("The sort process requires 3 parameters.");
System.err.println(" 1. The input file path.");
System.err.println(" 2. The output file path.");
System.err.print (" 3. The sort parameters in mainframe ");
System.err.println("sort format. Example: 15,5,CH,A");
} else {
new Sort(args[0], args[1], args[2]).run();
}
}
}