Data Structures having trouble with limited items sorted - java

I was playing around with such data structures in Java i figure out how to sort items on an Array or to an object. I want some words to be in spesific order I m able to use Bufferedreader HashMap, ArrayList. What i want to do is at any point after reading the first 42 lines, if some line is blank (i.e., a string of length 0) then output the line that occured 42 lines prior to that one. Also how can change this program to read the entire input one line at a time and then output the even numbered lines (starting with the first line, line 0) followed by the odd-numbered lines..I posted the code that i have so far.
public static void doIt(BufferedReader r, PrintWriter w) throws IOException {
ArrayList<String> s= new ArrayList<String>();
String line;
int n = 0;
while ((line = r.readLine()) != null) {
s.add(line);
n++;
}
Collections.sort(s);
Iterator<String> i = s.iterator();
while (i.hasNext()) {
w.println(i.next());
}
}
public static void main(String[] args) {
try {
BufferedReader r;
PrintWriter w;
if (args.length == 0) {
r = new BufferedReader(new InputStreamReader(System.in));
w = new PrintWriter(System.out);
} else if (args.length == 1) {
r = new BufferedReader(new FileReader(args[0]));
w = new PrintWriter(System.out);
} else {
r = new BufferedReader(new FileReader(args[0]));
w = new PrintWriter(new FileWriter(args[1]));
}
long start = System.nanoTime();
doIt(r, w);
w.flush();
long stop = System.nanoTime();
System.out.println("Execution time: " + 10e-9 * (stop-start));
} catch (IOException e) {
System.err.println(e);
System.exit(-1);
}
}

I'm not sure I understand your question correctly, but I hope this can help:
for printing the line that occurred 42 lines before an empty line, you can just keep a counter and once you find a line with zero length, output the line which have the index counter - 42 ( I might have an off by one error here )
int n = 0;
while ((line = r.readLine()) != null) {
if (n > 42 && s.length == 0)
System.out.println(s[n-42]);
s.add(line);
n++;
}
and for printing the even lines first then the odd ones, you can try reading two lines at a time, save the first line into an ArrayList, and the second line into a different one.
at the end, one will have the odd lines and one will have the even lines.
and one more last note, instead of using this:
Iterator<String> i = s.iterator();
while (i.hasNext()) {
w.println(i.next());
}
you can simply use this:
for( String line : s)
System.out.println(line)

Related

Filling each slot of an array with a line (String) from a text file

I have a text file list of thousands of String (3272) and I want to put them each into a slot of an Array so that I can use them to be sorted out. I have the sorting part done I just need help putting each line of word into an array. This is what I have tried but it only prints the last item from the text file.
public static void main(String[] args) throws IOException
{
FileReader fileText = new FileReader("test.txt");
BufferedReader scan = new BufferedReader (fileText);
String line;
String[] word = new String[3272];
Comparator<String> com = new ComImpl();
while((line = scan.readLine()) != null)
{
for(int i = 0; i < word.length; i++)
{
word[i] = line;
}
}
Arrays.parallelSort(word, com);
for(String i: word)
{
System.out.println(i);
}
}
Each time you read a line, you assign it to all of the elements of word. This is why word only ends up with the last line of the file.
Replace the while loop with the following code.
int next = 0;
while ((line = scan.readLine()) != null) word[next++] = line;
Try this.
Files.readAllLines(Paths.get("test.txt"))
.parallelStream()
.sorted(new ComImpl())
.forEach(System.out::println);

How to read a file from a specific line to another specific line?

So I'm trying to make a file reader to read from x line to y line but when i execute the program it reads all the lines of the file and not the lines that should have started and ended, For example if i'm looking an ID in the file it should print de ID, The name of the holder(the next line of the ID Line), and his/her address(Next line of the name Line), but instead of print just that it prints all the ID'S, Names and Addresses of everyone in the file.
System.out.println("Escriba el ID Del Cliente");
CL.setID(reader.next());
String line2;
int count = 0;
try {
BufferedReader input = new BufferedReader(new FileReader(file));
Scanner input2 = new Scanner(file);
PrintWriter output = new PrintWriter(new FileOutputStream(file, true));
LineNumberReader readers = new LineNumberReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
while((line2 = input.readLine()) != null)
{
if(line2.contains(CL.getID()))
{
while(((line2 = readers.readLine()) != null) && readers.getLineNumber() <= count + 3)
{
count++;
System.out.println(line2);
}
input.close();
input2.close();
output.close();
readers.close();
break;
}
}
}catch(IOException ex)
{
System.out.println("ERRORR!!!!!!");
}
I've modified your code because the problem was at the count++ which will eventually led to reading all the lines from your files, and at the line2 = readers.readLine() which will read from the first line of the file again ( the program works half correct because it reads only 3 lines and only if line2 contains your ID ). Now, to make your program work correctly, you need to either use the BufferedReader or the LineNumberReader.
public static void main(String[] args) {
System.out.println("Escriba el ID Del Cliente");
String line2;
File file = new File(yourpathhere);
int lineCount = 0;
try {
PrintWriter output = new PrintWriter(new FileOutputStream(file, true));
LineNumberReader readers = new LineNumberReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
while ((line2 = readers.readLine()) != null) {
lineCount++;
if (line2.contains(CL.getId())) {
while (line2 != null && readers.getLineNumber() <= lineCount + 3) {
System.out.println(line2);
line2 = readers.readLine();
}
output.close();
readers.close();
break;
}
}
} catch (IOException ex) {
System.out.println("ERRORR!!!!!!");
}
}
PS : pay attention for the getLineNumber() method because it increments the lines read until the moment you're calling it. It means that if we didn't had the lineCount and the ID we're trying to find was at the 6th line, the getLineNumber() value at the moment when line2.contains(CL.getId()) == true was 6, so the readers.getLineNumber() <= 3 will be FALSE and the program won't work correctly anymore. ( We need to keep track for the lines read until the moment we check for the id )
Assuming you have a file with 100 lines and you want to check and print out line 5 to 10 you could try this:
System.out.println("Escriba el ID Del Cliente");
CL.setID(reader.next());
String line;
int count = 0;
int xLine = 5;
int yLine = 10;
try (BufferedReader input = new BufferedReader(new FileReader(file)))
{
while((line = input.readLine()) != null)
{
if(count < xLine)
{
// skip all lines lower then start
continue;
}
else if(count >= xLine && count <= yLine && line.contains(CL.getID()))
{
// print line if line is between lines to read
// and if line contains ID
System.out.println(line);
}
else
{
// break if count is bigger then yLine
break;
}
count++;
}
}
catch(IOException ex)
{
System.out.println("ERRORR!!!!!!");
}
You read all lines till the BufferedReader reaches null. You check if the line contains your ID. Then you check if the count is between the linenumbers you want to check / print. Then you increment the count for the lines processed.
I simplified the try-catch-Block with a try-with-ressources Statement. As for now I don't see what your plans with output and scanner were, so I removed them.

Java - Read large .txt data file in batch size of 10

I have a large data file say dataset.txt where data is in the format -
1683492079 kyra maharashtra 18/04/2017 10:16:17
1644073389 pam delhi 18/04/2017 10:16:17
.......
The fields are id, name, state, and timestamp.
I have around 50,000 lines of data in the .txt data file.
My requirement is to read the data from this data file in batch size of 10.
So in first batch I need to read from 0 to 9th elements. Next batch from 10th to 19th elements and so on...
Using BufferedReader I have managed to read the whole file:
import java.io.*;
public class ReadDataFile {
public static void main(String args[]) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("dataset.txt"));
String line;
while((line = br.readLine())!= null)
{
System.out.println(line);
}
br.close();
}
}
But my requirement is to read the file in batch size of 10. I am new to Java so would really appreciate if some one can help me in simple terms.
As per #GhostCat answer - this what I have got -
public class ReadDataFile {
public static void main(String args[]) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("dataSetExample.txt"));
readBatch(br,10);
}
public static void readBatch(BufferedReader reader, int batchSize) throws IOException {
List<String> result = new ArrayList<>();
for (int i = 0; i < batchSize; i++) {
String line = reader.readLine();
if (line != null) {
// result.add(line);
System.out.println(line);
}
}
// return result;
return ;
}
}
The file is read in the readBatch method so how do I know in the main method that the end of file is reached to call the next 10 records? Kindly help.
Your requirements aren't really clear; but something simple to get you started:
A) your main method shouldn't do any reading; it just prepare that BufferedReader object
B) you use that reader with a method like:
private static List<String> readBatch(Reader reader, int batchSize) throws IOException {
List<String> result = new ArrayList<>();
for (int i = 0; i < batchSize; i++) {
String line = reader.readLine();
if (line != null) {
result.add(line);
} else {
return result;
}
}
return result;
}
To be used in your main:
BufferedReader reader = ...
int batchSize = 10;
boolean moreLines = true;
while (moreLines) {
List<String> batch = readBatch(reader, batchSize);
... do something with that list
if (batch.size() < batchSize) {
moreLines = false;
}
This is meant as "suggestion" how you could approach this. Things missing from my answer: probably you should use a distinct class, and do parsing right there (and return a List<DataClass> instead of moving around those raw "line strings".
And of course: 50000 lines isn't really much of data. Unless we are talking an embedded device, there is really not much point regarding "batch style".
And finally: the term batch processing has a very distinct meaning; also in Java, and if you intend to go there, see here for further reading.
Anybody in need of working example ---
// Create a method to read lines (using buffreader) and should accept the batchsize as argument
private static List<String> readBatch(BufferedReader br, int batchSize) throws IOException {
// Create a List object which will contain your Batch Sized lines
List<String> result = new ArrayList<>();
for (int i = 1; i < batchSize; i++) { // loop thru all your lines
String line = br.readLine();
if (line != null) {
result.add(line); // add your lines to your (List) result
} else {
return result; // Return your (List) result
}
}
return result; // Return your (List) result
}
public static void main(String[] args) throws IOException {
//input file
BufferedReader br = new BufferedReader(new FileReader("c://ldap//buffreadstream2.csv"));
//output file
BufferedWriter bw = new BufferedWriter(new FileWriter("c://ldap//buffreadstream3.csv"));
// Your Batch size i.e. how many lines you want in your batch
int batchSize = 5; // Define your batchsize here
String line = null;
long batchNumber = 1;
try {
List<String> mylist = null;
while ((line = br.readLine()) != null) { // Do it for your all line in your csv file
bw.write("Batch Number # " + batchNumber + "\n");
System.out.println("Batch Number # " + batchNumber);
bw.write(line + "\n"); // Since br.readLine() reads the next line you have to catch your first line here itself
System.out.println(line); // else you will miss every batchsize number line
// process your First Line here...
mylist = readBatch(br, batchSize); // get/catch your (List) result here as returned from readBatch() method
for (int i = 0; i < mylist.size(); i++) {
System.out.println(mylist.get(i));
// process your lines here...
bw.write(mylist.get(i) + "\n"); // write/process your returned lines
}
batchNumber++;
}
System.out.println("Lines are Successfully copied!");
br.close(); // one you are done .. dont forget to close/flush
br = null; // all
bw.flush(); // your
bw.close(); // BR and
bw = null; // BWs..
} catch (Exception e) {
System.out.println("Exception caught: " + e.getMessage()); // Catch any exception here
}
}

java regular expression getting values from a txt file [duplicate]

I am new to Java. I have one text file with below content.
`trace` -
structure(
list(
"a" = structure(c(0.748701,0.243802,0.227221,0.752231,0.261118,0.263976,1.19737,0.22047,0.222584,0.835411)),
"b" = structure(c(1.4019,0.486955,-0.127144,0.642778,0.379787,-0.105249,1.0063,0.613083,-0.165703,0.695775))
)
)
Now what I want is, I need to get "a" and "b" as two different array list.
You need to read the file line by line. It is done with a BufferedReader like this :
try {
FileInputStream fstream = new FileInputStream("input.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
int lineNumber = 0;
double [] a = null;
double [] b = null;
// Read File Line By Line
while ((strLine = br.readLine()) != null) {
lineNumber++;
if( lineNumber == 4 ){
a = getDoubleArray(strLine);
}else if( lineNumber == 5 ){
b = getDoubleArray(strLine);
}
}
// Close the input stream
in.close();
//print the contents of a
for(int i = 0; i < a.length; i++){
System.out.println("a["+i+"] = "+a[i]);
}
} catch (Exception e) {// Catch exception if any
System.err.println("Error: " + e.getMessage());
}
Assuming your "a" and"b" are on the fourth and fifth line of the file, you need to call a method when these lines are met that will return an array of double :
private static double[] getDoubleArray(String strLine) {
double[] a;
String[] split = strLine.split("[,)]"); //split the line at the ',' and ')' characters
a = new double[split.length-1];
for(int i = 0; i < a.length; i++){
a[i] = Double.parseDouble(split[i+1]); //get the double value of the String
}
return a;
}
Hope this helps. I would still highly recommend reading the Java I/O and String tutorials.
You can play with split. First find the line in the text that matches "a" (or "b"). Then do something like this:
Array[] first= line.split("("); //first[2] will contain the values
Then:
Array[] arrayList = first[2].split(",");
You will have the numbers in arrayList[]. Be carefull with the final brackets )), because they have a "," right after. But that is code depuration and it is your mission. I gave you the idea.

Infinite Loop in Java

So I'm trying to look at an input, and count words that fit a certain criteria (or rather, excluding words that I don't want to count). The error is in the following code:
BufferedReader br;
BufferedWriter bw;
String line;
int identifiers = 0;
boolean count = false;
try
{
br = new BufferedReader(new FileReader("A1.input"));
line = br.readLine();
while(line != null)
{
StringTokenizer t = new StringTokenizer(line);
String word;
System.out.println(t.countTokens()); //for testing, keeps printing 6
for(int c = 0; c < t.countTokens(); c++)
{
word = t.nextToken();
count = true;
if(Character.isDigit(word.charAt(0))) //if word begins with a number
{
count = false; //do not count it
}
if(count == true)
{
for(String s : keywords)
{
if(s.equals(word)) //if the selected word is a keyword
{
count = false; //do not count it
}
}
}
System.out.println(word); //testing purposes
}
word = t.nextToken();
}
Here is the input file:
INT f2(INT x, INT y )
BEGIN
z := x*x - y*y;
RETURN z;
END
INT MAIN f1()
BEGIN
INT x;
READ(x, "A41.input");
INT y;
READ(y, "A42.input");
INT z;
z := f2(x,y) + f2(y,x);
WRITE (z, "A4.output");
END
As stated in the comments in the code above, the first println statement prints 6 repeatedly (indicating to me that the while loop is endlessly repeating). The second "testing purposes" println statement continuously prints INT f2(INT x repeatedly.
It looks like you're never actually reading the next line of the file. Change this bit:
try
{
br = new BufferedReader(new FileReader("A1.input"));
line = br.readLine();
while(line != null)
{
to this:
try
{
br = new BufferedReader(new FileReader("A1.input"));
while((line = br.readLine()) != null)
{
Your use of while() is evaluating the current line only; thus, it's never null. Change it to if().

Categories

Resources