I have a text file which is read in. It has delimeters which are <.> . There is a main subject then there are three paragraphs. Lets say title, section1, section2, section3, and then the next article.
How can I store the data so that ArrayList one will have all the titles, ArrayList 2 will have all the section1 information, etc.? I want be able to output these arrays.
E.g.:
Large storm on its way.
about the large storm
statics on storms
conclusions about storms
The example above shows what one record would look like.
public void read()
{
try
{
FileReader fr = new FileReader(file_path);
BufferedReader br = new BufferedReader(fr);
String s = "";
// keep going untill there is no input left and then exit
while((s = br.readLine()) != null)
{ }
fr.close();
}
catch (Exception e)
{
System.err.println("Error: read() " + e.getMessage());
}
}
public static void main(String [] args)
{
Reader reader = new ResultsReader("C:/data.txt");
reader.read();
String output = ((ResultsReader)reader).getInput();
String str = "title<.>section1<.>section2<.>";
String data[] = str.split("<.>");
}
I am not sure how to store the data in separate ArrayLists so that they can be traversed.
You cannot create arrays and put the data into them, because you don't know how large to create the arrays. So, use a list instead and then turn them into arrays after you have finished reading the file:
List tilesList = new ArrayList<String>();
// etc.
FileReader fr = new FileReader(file_path);
BufferedReader br = new BufferedReader(fr);
String s = null // I think this should be null, so that if there are no lines,
// you don't have problems with str.split();
while((s = br.readLine()) != null) {
String[] line = str.split("<.>");
tilesList.add(line[1]);
// etc.
}
fr.close();
String[] tiles = tilesList.toArray(new String[tilesList.size()]);
// etc.
Related
In my code I have two files in my drive those two files have some text and I want to display those string in the console and also remove the repeated string and display the repeated string once rather than displaying it twice.
Code:
public class read {
public static void main(String[] args) {
try{
File file = new File("D:\\file1.txt");
FileReader fileReader = new FileReader(file);
BufferedReader br = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
while((line = br.readLine()) != null){
stringBuffer.append(line);
stringBuffer.append("\n");
}
fileReader.close();
System.out.println("Contents of file1:");
String first = stringBuffer.toString();
System.out.println(first);
File file1 = new File("D:\\file2.txt");
FileReader fileReader1 = new FileReader(file1);
BufferedReader br1 = new BufferedReader(fileReader1);
StringBuffer stringBuffer1 = new StringBuffer();
String line1;
while((line1 = br1.readLine()) != null){
stringBuffer1.append(line1);
stringBuffer1.append("\n");
}
fileReader1.close();
System.out.println("Contents of file2:");
String second = stringBuffer1.toString();
System.out.println(second);
System.out.println("answer:");
System.out.println(first+second);
}catch (IOException e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
Output is:
answer:
hi hello
how are you
hi ya
i am fine
But I want to compare both the strings and if the same string repeated then that string should be displayed once.
Output I expect is like this:
answer:
hi hello
how are you
ya
i am fine
Where the "hi" is found in both the strings so that I need to delete the one duplicate string.
How can I do that please help.
Thanks in advance.
You can pass your lines through this method to parse out duplicate words:
// store unique previous words
static Set<String> words = new HashSet<>();
static String removeDuplicateWords(String line) {
StringJoiner sj = new StringJoiner(" ");
// split on whitespace to get distinct words
for (String word : line.split("\\s+")) {
// try to add word to the set
if (words.add(word)) {
// if the word was added (=not seen before), append to the result
sj.add(word);
}
}
return sj.toString();
}
I am a little stuck with a java exercise I am currently working on. I have a text file in this format:
Quio Kla,2221,3.6
Wow Pow,3332,9.3
Zou Tou,5556,9.7
Flo Po,8766,8.1
Andy Candy,3339,6.8
I now want to calculate the average of the whole third column, but I have to extract the data first I believe and store it in an array. I was able to read all the data with a buffered reader and print out the entire file in console, but that did not get me closer to get it into an array. Any suggestions on how I can read in a specific column of a text file with a buffered readder into an array would be highly appreciated.
Thank you very much in advance.
You can split your text file by using this portion of code:
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader("textfile.txt"));
String read = null;
while ((read = in.readLine()) != null) {
String[] splited = read.split(",");
for (String part : splited) {
System.out.println(part);
}
}
} catch (IOException e) {
System.out.println("There was a problem: " + e);
e.printStackTrace();
} finally {
try {
in.close();
} catch (Exception e) {
}
}
And then you'll have all your columns in the array part.
It`s definitely not the best solution, but should be sufficient for you
BufferedReader input = new BufferedReader(new FileReader("/file"));
int numOfColumn = 2;
String line = "";
ArrayList<Integer>lines = new ArrayList<>();
while ((line = input.readLine()) != null) {
lines.add(Integer.valueOf(line.split(",")[numOfColumn-1]));
}
long sum =0L;
for(int j:lines){
sum+=j;
}
int avg = (int)sum/lines.size();
I'm going to assume each data set is separated by newline characters in your text file.
ArrayList<Double> thirdColumn = new ArrayList<>();
BufferedReader in = null;
String line=null;
//initialize your reader here
while ((line = in.readLine())!=null){
String[] split = line.split(",");
if (split.length>2)
thirdColumn.add(Double.parseDouble(split[2]));
}
By the end of the while loop, you should have the thirdColumn ArrayList ready and populated with the required data.
The assumption is made that your data set has the following standard format.
String,Integer,Double
So naturally a split by a comma should give a String array of length 3, Where the String at index 2 contains your third column data.
I am trying to complete a little program.
I've got a text file (.txt) to store different data on objects that i've got.
The structure of the file is the next (exemples data.txt) :
Sedane
2005
195000
Diesel
Blue
SUV
2013
34000
Fuel
Black
Each object is made true a class that i've build called Cars.
So the 1 line is the type of car, the 2nd the year of built, the 3rd line is the milage, the 4th is the type of fuel, and the 5th line is the color of the car.
So basicly i need to open the file, and load the data into the memory when i execute my program into an array with object in it.
I'm ok to open the file but i'm blocked when it comes to reading the data and putting it in an array.
The array size is 2 for this exemple, but if i have more entries in the file it's going to adapt it's size when loading at the startup of the program.
Here's what i've got unti now (for my code ...)
public static void loadCars () {
FileReader fopen;
BufferedReader opened;
String line;
try {
fEntree = new FileReader( "data.txt" );
opened = new BufferedReader( fopen );
while ( opened.ready() ) {
line = opened.readLine();
// Don't know what to do here ????
}
opened.close();
} catch ( IOException e ) {
System.out.println( "File doesn't exist !" );
}
}
Someting like this will do the trick. I'm adding the file contents line by line to an Arraylist instead of an array though. This way you don't have to know how big your array needs to be before hand. Plus you can always change it to an array later.
public ArrayList<String> readFileToMemory(String filepath)
{
in = new BufferedReader(new FileReader( "data.txt" ));
String currentLine = null;
ArrayList<String> fileContents = new ArrayList<String>();
try
{
while((currentLine = in.readLine()) != null)
{
fileContents.add(currentLine);
}
}
catch(IOException e)
{
e.printStackTrace();
}
finally
{
try
{
in.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
return fileContents;
}
LineNumberReader lnr = new LineNumberReader(new FileReader(new File("File1")));
lnr.skip(Long.MAX_VALUE);
long length = lnr.getLineNumber();
lnr.close();
in = new BufferedReader(new FileReader( "data.txt" ));
Car[] cars= new Car[length/5];
String currentLine;
int i=0;
for(int i=0;i<length/5;i+=5) {
String name = in.readLine();
String year = in.readLine();
String miles = in.readLine();
String gas = in.readLine();
String color = in.readLine();
cars[i] = new Car(name,year,miles,gas,color);
}
You'll have to handle exceptions too, surround stuff in try catch structures.
You can look at my solution here below (I also corrected/simplified some problems with the variables for reading the file, anyway this was not the main topic):
public static void loadCars() {
FileReader fopen;
BufferedReader opened;
String line;
ArrayList<Car> carList = new ArrayList<Car>();
try {
fopen = new FileReader("data.txt");
opened = new BufferedReader(fopen);
int nFields = 5; // we have 5 fields in the Car class
String[] fields = new String[nFields]; // to temporary store fields values read line by line
int lineCounter = 0;
while ((line = opened.readLine()) != null) {
fields[lineCounter] = line;
lineCounter++;
if ((lineCounter) % nFields == 0) { //it means we have all 5 fields values for a car
carList.add(new Car(fields)); //therefore we create a new car and we add it to the list of cars
}
}
opened.close();
} catch (IOException e) {
System.out.println("File doesn't exist !");
}
}
Basically we use an ArrayList to store all the cars, and we read the file, waiting to have all the fields values in order to create the Car object. I store the fields values in an array of Strings: I don't know how you implemented the Car class, but maybe it is useful to create a constructor that takes as parameter an array of strings, so it can set the fields, for instance:
class Car {
private String type;
private String year;
private String milage;
private String fuel;
private String color;
public Car(String[] fields) {
type=fields[0];
year=fields[0];
milage=fields[0];
fuel=fields[0];
type=fields[0];
}
}
But I've to say that probably this is a little 'too static'.
For simplicity I assumed that all your fields are of String type, but probably fields like 'year' or 'milage' might be of int type. In this case you can use array of Object[] (instead of String[]), and then cast the value with the right type.
I hope this may help you.
I have a text file which has 10 fields(columns)each separated by a tab.And i have several such rows.I wish to read the text file, split it for every column, using a "tab" delimiter and then storing it in an array of 10 columns and unlimited rows.Can that be done?
An array can't have "unlimited rows" - you have to specify the number of elements on construction. You might want to use a List of some description instead, e.g. an ArrayList.
As for the reading and parsing, I'd suggest using Guava, particularly:
Files.newReaderSupplier
CharStreams.readLines
Splitter
(That lets you split the lines as you go... alternatively you could use Files.readLines to get a List<String>, and then process that list separately, again using Splitter.)
BufferedReader buf = new BufferedReader(new FileReader(fileName));
String line = null;
List<String[]> rows = new ArrayList<String[]>();
while((line=buf.readLine())!=null) {
String[] row = line.split("\t");
rows.add(row);
}
System.out.println(rows.toString()); // rows is a List
// use rows.toArray(...) to convert to array if necessary
Here is a simple way to load a .txt file and store it into a array for a set amount of lines.
import java.io.*;
public class TestPrograms {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
String conent = new String("da");
String[] daf = new String[5];//the intiger is the number of lines +1 to
// account for the empty line.
try{
String fileName = "Filepath you have to the file";
File file2 = new File(fileName);
FileInputStream fstream = new FileInputStream(file2);
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
int i = 1;
while((conent = br.readLine()) != null) {
daf[i] = conent;
i++;
}br.close();
System.out.println(daf[1]);
System.out.println(daf[2]);
System.out.println(daf[3]);
System.out.println(daf[4]);
}catch(IOException ioe){
System.out.print(ioe);
}
}
}
I can successfully read text file using InputFileStream and Scanner classes. It's very easy but I need to do something more complex than that. A little background about my project first.. I have a device with sensors, and I'm using logger that will log every 10sec data from sensors to a text file. Every 10 sec its a new line of data. So what I want is when I read a file is to grab each separate sensor data into an array. For example:
velocity altitude latitude longitude
22 250 46.123245 122.539283
25 252 46.123422 122.534223
So I need to grab altitude data (250, 252) into an array alt[]; and so forth vel[], lat[], long[]...
Then the last line of the text file will different info, just a single line. It will have the date, distance travelled, timeElapsed..
So after doing a little research I came across InputStream, Reader, StreamTokenizer and Scanner class. My question is which one would you recommend for my case? Is it possible to do what I need to do in my case? and will it be able to check what the last line of the file is so it can grab the date, distance and etc.. Thank you!
Reader + String.split()
String line;
String[] values;
BufferedReader reader = new BufferedReader(new FileReader(args[0]));
List<Integer> velocity = new ArrayList<Integer>();
List<Integer> altitude = new ArrayList<Integer>();
List<Float> latitude = new ArrayList<Float>();
List<Float> longitude = new ArrayList<Float>();
while (null != (line = reader.readLine())) {
values = line.split(" ");
if (4 == values.length) {
velocity.add(Integer.parseInt(values[0]));
altitude.add(Integer.parseInt(values[1]));
latitude.add(Float.parseFloat(values[2]));
longitude.add(Float.parseFloat(values[3]));
} else {
break;
}
}
If you need arrays not list:
velocity.toArray();
As far I undestand data lines has 4 items and last line has 3 items (date, distance, elapsed time)
I would use Scanner. Take a look at the examples here. Another option for you to use BufferedReader to read a line and then have parse method to parse that line into the tokens you want.
Also you might find this thread to be useful.
Very quick code base on the link above. The inputs array has your file data tokens.
public static void main(String[] args) {
BufferedReader in=null;
List<Integer> velocityList = new ArrayList<Integer>();
List<Integer> altitudeList = new ArrayList<Integer>();
List<Double> latitudeList = new ArrayList<Double>();
List<Double> longitudeList = new ArrayList<Double>();
try {
File file = new File("D:\\test.txt");
FileReader reader = new FileReader(file);
in = new BufferedReader(reader);
String string;
String [] inputs;
while ((string = in.readLine()) != null) {
inputs = string.split("\\s");
//here is where we copy the data from the file to the data stucture
if(inputs!=null && inputs.length==4){
velocityList.add(Integer.parseInt(inputs[0]));
altitudeList.add(Integer.parseInt(inputs[1]));
latitudeList.add(Double.parseDouble(inputs[2]));
longitudeList.add(Double.parseDouble(inputs[3]));
}
}
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
if(in!=null){
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
//here are the arrays you want!!!
Integer [] velocities = (Integer[]) velocityList.toArray();
Integer [] altitiudes = (Integer[]) altitudeList.toArray();
Double [] longitudes = (Double[]) longitudeList.toArray();
Double [] latitudes = (Double[]) latitudeList.toArray();
}
As your data is relatively simple, BufferedReader and StringTokenizer should do the trick. You'll have to read ahead by one line to detect when there are no more lines left.
Your code could be something like this
BufferedReader reader = new BufferedReader( new FileReader( "your text file" ) );
String line = null;
String previousLine = null;
while ( ( line = reader.readLine() ) != null ) {
if ( previousLine != null ) {
//tokenize and store elements of previousLine
}
previousLine = line;
}
// last line read will be in previousLine at this point so you can process it separately
But how you process the line itself is really up to you, you can use Scanner if you're feeling more comfortable with it.