Reading a wordpad file with 3 columns in Java - java

I want to read a text file containing space sepearted values. Values are integers. How can I read it? I want to read each line and after go to next.
The contents are as the example:
"12/11/2012" "00.00.01" 0,100
"12/11/2012" "00.00.05" 0,140
"12/11/2012" "00.00.09" 0,240
"12/11/2012" "00.00.13" 0,247
The first column is the date, the second is second and the third is litres.
How can I do it with a Java program?
I think of using Scanner class. I made this program:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ScannerExample {
public static void main(String args[]) throws FileNotFoundException {
File text = new File("C:\Users\Desktop\test\test.txt");
Scanner scnr = new Scanner(text);
int lineNumber = 1;
while(scnr.hasNextLine()){
String line = scnr.nextLine();
System.out.println("line " + lineNumber + " :" + line);
lineNumber++;
}
}
}
But I haven't the result that I would like to have.
Any help?

The easiest in Java is to use Apache Commons Libraries.
Just add the following dependency in your pom file (if you are using maven)
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>
Then you can do
File file = new File("yourFile.txt");
List<String> lines = FileUtils.readLines(file);
You will get each of line of your file in the list. Then to get the content of your file:
for(String line : lines){
String[] columns = line.split(" ") //because your columns seem to be separated by a white space
}
The array columns will contain your data
DateFormat format = new SimpleDateFormat("dd/mm/yyyy");
//column 1
Date date = format.format(column[0]);
//column 2
//I'm not sure to get your second column, is it just second or can it be more?
//column 3
double litres = Double.parseDouble(column[2]);

This looks like a CSV file. You could use a CSV tool to read it.
I know CSV means 'comma separated values', and your file doesn't have commas, but CSV tools can also read files separated by space.

This would be done by simple google search as well.. first you would find code like this:
import java.io.*;
class FileRead
{
public static void main(String args[])
{
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("textfile.txt");
// Use DataInputStream to read binary NOT text.
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
Replace the System.out.println with some code to get all content from " to " Like:
while ((strLine = br.readLine()) != null) {
int start = 1, pos = 0,lastpos= 1;
String dates, times, values;
if(strLine.indexOf("\"",lastpos) > 0){
pos = strLine.indexOf("\"",lastpos);
dates = strLine.substring(start,pos);
lastpos = pos+3;//replace through search for \"
pos = strLine.indexOf("\"",lastpos);
times = strLine.substring(lastpos,pos);
lastpos = pos+2;//replace through search for \"
values = strLine.substring(lastpos,strLine.length());
System.out.println(dates);//Convert to Date
System.out.println(times);//Convert to time
System.out.println(values);//Convert to Integer.valueOf/)
System.out.println("next line");
}
}

Related

The content of my text file is not showing when I run the program

I'm trying to read the contents of a text file and print them. I cannot figure out why the content is not displayed when I run the program.
This is my code:
import java.io.*;
import java.util.Scanner;
public class ReadTxtfile{
public static void main (String [] args) throws IOException{
Scanner input = new Scanner(System.in);
//Open the file
File file = new File("chessfile.txt");
//Open files for reading
Scanner inputFile = new Scanner(file);
while(!file.exists()){
System.out.println("The file chessfile.txt is not found.");
System.exit(0);
}
//Read lines from the file
while(inputFile.hasNext());
//Read next
String piece = inputFile.nextLine();
String color = inputFile.nextLine();
String column = inputFile.nextLine();
String row = inputFile.nextLine();
//Display File
System.out.printf(piece, color, column, row);
//Close file
inputFile.close();
}
}//End of main
A few things first you dont want to loop while the file exists and then use system.exit if you really need to just use an if statement
if(!file.exists()){
System.out.println("The file chessfile.txt is not found.");
System.exit(0);
}
Second your going to want to use file.hasNextLine() instead of hasNext and also where are the curly braces for your loop this is what it should look like.
while(inputFile.hasNextLine()){
String piece = inputFile.nextLine();
String color = inputFile.nextLine();
String column = inputFile.nextLine();
String row = inputFile.nextLine();
}
Finnnaly i guess with printf your trying to display them neatly well you cant do that outside of the loop so instead of doing all that nonsense create a String array and store each of the lines in that as you get the different values. Assuming that your data is on seperate lines it should look somewhat like this.
ArrayList<String> peices = new ArrayList<String>();
while(inputFile.hasNextLine()){
String peice = "";
peice += inputFile.nextLine() + " ";
peice += inputFile.nextLine() + " ";
peice += inputFile.nextLine() + " ";
peice += inputFile.nextLine() + " ";
peices.add(peice);
}
And finnaly to display them on multiple lines you should use a simple enhanced loop.
for(String i : peices) {
System.out.println(i);
}
your while loop is not working. so next line data not coming in a string object.
and if you want getting all your text file data in one line try below loop.
String line ="";
while(scanner.hasNextLine())
line += scanner.nextLine();
System.out.printf(line );

Java: Read from Multiple Lines (External File)

I am trying to display the contents of multiple rows in a text file. I can do it no problem with a single line, but I add another line and I'm not sure what I need to add to my code to make it move on to the next line. I need myValues[1] to be the same as myValues[n] only to be the second line in the file. I believe I need to se a new String as the next line but I'm not sure exactly how with this setup.
package a3;
import java.io.*;
public class A3
{
public static void main(String [] args)
{
String animals = "animals.txt";
String line = null;
try
{
FileReader fileReader = new FileReader(animals);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String aLine = bufferedReader.readLine();
String myValues[] = aLine.split(" ");
int n = 0;
while((line = bufferedReader.readLine()) != null)
{
System.out.println(myValues[n] + " " + myValues[1]);
n++;
}
bufferedReader.close();
}
catch(FileNotFoundException ex)
{
System.out.println("Unable to open file '" + animals + "'");
}
catch(IOException ex)
{
System.out.println("Error reading file '" + animals + "'");
}
}
}
Here is another simple way to read lines from a file and do the processing:
There is a java.io.LineNumberReader class which helps do it.
Sample snippet:
LineNumberReader lnr = new LineNumberReader(new FileReader(new File(filename)));
String line = null;
while ((line = lnr.readLine()) != null)
{
// Do you processing on line
}
In your code, the array myValues is never changed and always contains the values for the first line of text. You need to change it each time you get a new line, this is done in your while loop :
[...]
while((line = bufferedReader.readLine()) != null)
{
myValues[] = line.split(" ");
System.out.println(myValues[n] + " " + myValues[1]);
n++;
}
Obviously not tested...
You could also read all lines to a String list like this:
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.util.List;
List<String> lines = Files.readAllLines(new File(animals).toPath(), Charset.defaultCharset());
And than iterate over the line list, split the values and output them.

Reading text files in Java and using data

I am required to evaluate the contents of a .txt file, the file includes 5 numbers, all spaced apart by one (ex: 5555 55 45 47 85) on one line.
The problem isn't reading the file, but actually using each number in the file.
Question: How can I grab the 5 numbers and store each into a unique variable?
Code so far:
import java.io.FileReader;
import java.io.BufferedReader;
public class PassFail {
public static void main(String[] args) {
try{
FileReader file = new FileReader("C:\\new_java\\Final_Project\\src\\student.txt");
BufferedReader reader = new BufferedReader(file);
String line = reader.readLine();
reader.close();
System.out.println(line);
} catch(Exception e) {System.out.println("Error:"+ e);}
}
}
You need to read the file line by line, which you already did. Then you can split the string on space character and iterate over the fields and parse them to Integer
s= reader.readline()
String tokens[]= s.split(" ");
int nums[] = new int[tokens.length];
for(int i=0; i<tokens.lenght; i++) {
nums[i] = Integer.parseInt(tokens[i]);
}
Hope this helps.

Adding data from .txt document to array

Below is what the text document looks like. The first line is the number of elements that I want the array to contain. The second is the ID for the product, separated by # and the third line is the total price of the products once again separated by #
10
PA/1234#PV/5732#Au/9271#DT/9489#HY/7195#ZR/7413#bT/4674#LR/4992#Xk/8536#kD/9767#
153#25#172#95#235#159#725#629#112#559#
I want to use the following method to pass inputFile to the readProductDataFile method:
public static Product[] readProductDataFile(File inputFile){
// Code here
}
I want to create an array of size 10, or maybe an arrayList. Preferably to be a concatenation of Customer ID and the price, such as Array[1] = PA/1234_153
There you go the full class, does exactly what you want:
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Arrays;
import java.io.FileNotFoundException;
import java.io.IOException;
class myRead{
public static void main(String[] args) throws FileNotFoundException, IOException {
BufferedReader inputFile = new BufferedReader(new FileReader("test.txt"));
String numberOfElements = inputFile.readLine();
//this is the first line which contains the number "10"
//System.out.println(numberOfElements);
String secondLine = inputFile.readLine();
//this is the second line which contains your data, split it using "#" as a delimiter
String[] strArray = secondLine.split("#");
//System.out.println(Arrays.toString(strArray));
//System.out.println(strArray[0]);
String thirdLine = inputFile.readLine();
//this is the third line which contains your data, split it using "#" as a delimiter
String[] dataArray = thirdLine.split("#");
//combine arrays
String[] combinedArray = new String[strArray.length];
for (int i=0;i<strArray.length;i++) {
combinedArray[i]=strArray[i]+"_"+dataArray[i];
System.out.println(combinedArray[i]);
}
}
}
OUTPUT:
PA/1234_153
PV/5732_25
Au/9271_172
DT/9489_95
HY/7195_235
ZR/7413_159
bT/4674_725
LR/4992_629
Xk/8536_112
kD/9767_559
The trick in what I am doing is using a BufferedReader to read the file, readLine to read each of the three lines, split("#"); to split each token using the # as the delimiter and create the arrays, and combinedArray[i]=strArray[i]+"_"+dataArray[i]; to put the elements in a combined array as you want...!
public static Product[] readProductDataFile(File inputFile){
BufferedReader inputFile = new BufferedReader(new FileReader(inputFile));
// the rest of my previous code goes here
EDIT: Everything together with calling a separate method from inside the main, with the file as an input argument!
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Arrays;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.File;
class myRead{
public static void main(String[] args) throws FileNotFoundException, IOException {
File myFile = new File("test.txt");
readProductDataFile(myFile);
}
public static String[] readProductDataFile(File inputFile) throws FileNotFoundException, IOException{
BufferedReader myReader = new BufferedReader(new FileReader("test.txt"));
String numberOfElements = myReader.readLine();
//this is the first line which contains the number "10"
//System.out.println(numberOfElements);
String secondLine = myReader.readLine();
//this is the second line which contains your data, split it using "#" as a delimiter
String[] strArray = secondLine.split("#");
//System.out.println(Arrays.toString(strArray));
//System.out.println(strArray[0]);
String thirdLine = myReader.readLine();
//this is the third line which contains your data, split it using "#" as a delimiter
String[] dataArray = thirdLine.split("#");
//combine arrays
String[] combinedArray = new String[strArray.length];
for (int i=0;i<strArray.length;i++) {
combinedArray[i]=strArray[i]+"_"+dataArray[i];
System.out.println(combinedArray[i]);
}
return combinedArray;
}
}
OUTPUT
PA/1234_153
PV/5732_25
Au/9271_172
DT/9489_95
HY/7195_235
ZR/7413_159
bT/4674_725
LR/4992_629
Xk/8536_112
kD/9767_559
You don't even need the first line. Just read the second line directly into a single string and then split it by using String,split() method.
Read more for split method here.
You could use something like this (Be aware that i can't test it at the moment)
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader("fileeditor.txt"));
String read = null;
String firstLine=in.readLine();
//reads the first line
while ((read = in.readLine()) != null) {
// reads all the other lines
read = in.readLine();
String[] splited = read.split("#");
//split the readed row with the "#" character
for (String part : splited) {
System.out.println(part);
}
}
} catch (IOException e) {
System.out.println("There was a problem: " + e);
e.printStackTrace();
} finally {
try {
//close file
in.close();
} catch (Exception e) {
}
}
This is how you can do it using Java (don't forget to import):
public static Product[] readProductDataFile(File inputFile){
Scanner s = new Scanner(inputFile);
String data = "";
while(s.hasNext())
data += s.nextLine();
String[] dataArray = data.split("#");
}
You can try this way ..
Reading line by line and storing each row in a array.
Use while storing so it will split and save .
String[] strArray = secondLine.split("#");
Now use the for loop and concat the values as u wish and save ina third array .
For(int i=0 ;i< file.readline;i++)
{
string s = a[customerid];
s.concat(a[productid]);
a[k] =s;
}

Reading in a file and processing data

I am a noobie at programming and I can't seem to figure out what to do.
I am to write a Java program that reads in any number of lines from a file and generate a report with:
the count of the number of values read
the total sum
the average score (to 2 decimal places)
the maximum value along with the corresponding name.
the minimum value along with the corresponding name.
The input file looks like this:
55527 levaaj01
57508 levaaj02
58537 schrsd01
59552 waterj01
60552 boersm01
61552 kercvj01
62552 buttkp02
64552 duncdj01
65552 beingm01
I program runs fine, but when I add in
score = input.nextInt(); and
player = input.next();
The program stops working and the keyboard input seems to stop working for the filename.
I am trying to read each line with the int and name separately so that I can process the data and complete my assignment. I don't really know what to do next.
Here is my code:
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Scanner;
public class Program1 {
private Scanner input = new Scanner(System.in);
private static int fileRead = 0;
private String fileName = "";
private int count = 0;
private int score = 0;
private String player = "";
public static void main(String[] args) {
Program1 p1 = new Program1();
p1.getFirstDecision();
p1.readIn();
}
public void getFirstDecision() { //*************************************
System.out.println("What is the name of the input file?");
fileName = input.nextLine(); // gcgc_dat.txt
}
public void readIn(){ //*********************************************
try {
FileReader fr = new FileReader(fileName + ".txt");
fileRead = 1;
BufferedReader br = new BufferedReader(fr);
String str;
int line = 0;
while((str = br.readLine()) != null){
score = input.nextInt();
player = input.next();
System.out.println(str);
line++;
score = score + score;
count++;
}
System.out.println(count);
System.out.println(score);
br.close();
}
catch (Exception ex){
System.out.println("There is no shop named: " + fileName);
}
}
}
The way you used BufferReader with Scanner is totally wrong .
Note: you can use BufferReader in Scanner constructor.
For example :
try( Scanner input = new Scanner( new BufferedReader(new FileReader("your file path goes here")))){
}catch(IOException e){
}
Note: your file reading process or other processes must be in try block because in catch block you cannot do anything because your connection is closed. It is called try catch block with resources.
Note:
A BufferedReader will create a buffer. This should result in faster
reading from the file. Why? Because the buffer gets filled with the
contents of the file. So, you put a bigger chunk of the file in RAM
(if you are dealing with small files, the buffer can contain the whole
file). Now if the Scanner wants to read two bytes, it can read two
bytes from the buffer, instead of having to ask for two bytes to the
hard drive.
Generally speaking, it is much faster to read 10 times 4096 bytes
instead of 4096 times 10 bytes.
Source BufferedReader in Scanner's constructor
Suggestion: you can just read each line of your file by using BufferReader and do your parsing by yourself, or you can use Scanner class that gives you ability to do parsing tokens.
difference between Scanner and BufferReader
As a hint you can use this sample for your parsing goal
Code:
String input = "Kick 20";
String[] inputSplited = input.split(" ");
System.out.println("My splited name is " + inputSplited[0]);
System.out.println("Next year I am " + (Integer.parseInt(inputSplited[1])+1));
Output:
My splited name is Kick
Next year I am 21
Hope you can fixed your program by given hints.

Categories