Reading text files in Java and using data - java

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.

Related

Result of Java split() is varies when working with string of numbers

Why does Java String.split() generate different results when working with string defined in code versus string read from a file when numbers are involved? Specifically I have a file called "test.txt" that contains chars and numbers separated by spaces:
G H 5 4
The split method does not split on spaces as expected. But if a string variable is created within code with same chars and numbers separated by spaces then the result of split() is four individual strings, one for char and number. The code below demonstrates this difference:
import java.io.File;
import java.io.FileReader;
import java.io.BufferedReader;
public class SplitNumber {
//Read first line of text file
public static void main(String[] args) {
try {
File file = new File("test.txt");
FileReader fr = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fr);
String firstLine;
if ((firstLine = bufferedReader.readLine()) != null) {
String[] firstLineNumbers = firstLine.split("\\s+");
System.out.println("First line array length: " + firstLineNumbers.length);
for (int i=0; i<firstLineNumbers.length; i++) {
System.out.println(firstLineNumbers[i]);
}
}
bufferedReader.close();
String numberString = "G H 5 4";
String[] numbers = numberString.split("\\s+");
System.out.println("Numbers array length: " + numbers.length);
for (int i=0; i<numbers.length; i++) {
System.out.println(numbers[i]);
}
} catch(Exception exception) {
System.out.println("IOException occured");
exception.printStackTrace();
}
}
}
The result is:
First line array length: 3
G
H
5 4
Numbers array length: 4
G
H
5
4
Why do the numbers from the file not get parsed the same as the same string defined within code?
Based on feedback I changed the regex to split("[\\s\\h]+") which resolved the issue; the numbers for the file were properly split which clearly indicated that I had a different whitespace-like character in the text file that I was using. I then replaced the contents of the file (using notepad) and reverted back to split("\\s+") and found that it worked correctly this time. So at some point I must have introduced different white-space like characters in the file (maybe a copy/paste issue). In the end the take away is I should use split("[\\s\\h]+") when reading from a file where I want to split on spaces as it will cover more scenarios that may not be immediately obvious.
Thanks to all for helping me find the root cause of my issue.

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;
}

BufferedReader sometimes read text, sometimes doesn't

I'm trying to read from a .java the methods I have on it, also the classes, I'm using taggs to identify them and stored them, the problem is that using BufferedReader sometimes just doesn't work, the buffer skips a lot of lines for a reason that I can't understand, sometimes when checking the file by myself I just put random spaces between lines, and that fixes some parts, but I can't get the Buffer read all my text without skipping anything, my code so far is like this:
public class ReadFile {
public static void main(String[] args) {
int numclas=0,numbase=0,numbaseagr=0,numbmet=0,numag=0;
String mt="//MT";
String[] nomclass2 = new String[10];
String[] nommetodo2 = new String[50];
boolean metodo=false;
BufferedReader in = null;
try {
in = new BufferedReader(new FileReader("\\Program.java"));
String read = null;
while ((read = in.readLine()) != null) {
read = in.readLine();
String[] splited = read.trim().split("\\s+");
for(int i=0;i<splited.length;i++){
System.out.println(splited[i]);
if(splited[i].equals("class")){
nomclass2[numclas]=splited[i+1];
numclas=numclas+1;
}
if (splited[i].equals(mt)){
metodo=true;
}
if (splited[i].equals("public")){
if (splited[i+1].equals("static")){
nommetodo2[numbmet]=splited[i+3];
numbmet=numbmet+1;
}
if (splited[i+1].equals("int")||splited[i+1].equals("double")||splited[i+1].equals("String")||splited[i+1].equals("boolean")){
nommetodo2[numbmet]=splited[i+2];
numbmet=numbmet+1;
}
if (splited[i].equals("int")||splited[i].equals("double")||splited[i].equals("String")||splited[i].equals("boolean")){
nommetodo2[numbmet]=splited[i+1];
numbmet=numbmet+1;
}
metodo=false;
}
if ((splited[i].equals("int")||splited[i].equals("double")||splited[i].equals("String")||splited[i].equals("boolean"))&&metodo){
nommetodo2[numbmet]=splited[i+1];
numbmet=numbmet+1;
metodo=false;
}
}
}
} catch (IOException e) {
System.out.println("There was a problem: " + e);
e.printStackTrace();
} finally {
try {
in.close();
} catch (Exception e) {
}
}
Now let me show you the .java I'm trying to read:
import java.text.DecimalFormat;
import java.io.*;
//Main file of the program 1
public class Program1 {
//MT
public static void main (String args []) {
DecimalFormat format=new DecimalFormat("##.##");
System.out.println("How many data do you want to insert?");
int num=Leer.Int();
Fila lista=new Fila();
Fila lista2=new Fila();
double x=0.0;
for(int i=0;i<num;i++){
x=Leer.Double();
lista.addNum(x);
}
double prom=0.0;
double desv=0.0;
prom=lista.getprom();
desv=lista.getdevst();
System.out.println("The mean for column 1 is: "+format.format(prom));
System.out.println("The Std.Dev for column 1 is: "+format.format(desv));
System.out.println("How many data do you want to insert?");
num=Leer.Int();
x=0.0;
for(int i=0;i<num;i++) {
x=Leer.Double();
lista2.addNum(x);
}
prom=0.0;
desv=0.0;
prom=lista2.getprom();
desv=lista2.getdevst();
System.out.println("The mean for column 2 is: "+format.format(prom));
System.out.println("The Std.Dev for column 2 is: "+format.format(desv));
}
}
And the result when I print the array
Date:
12/12/12
import
java.text.DecimalFormat;
//Main
file
of
the
program
1
//MT
DecimalFormat
format=new
DecimalFormat("##.##");
so on...
See how in the //MT the Buffer skips a lot of lines, a lot of this is happening (see how it ignores the first lines of the program), and I don't know how to fix it, because sometimes when I try to "fix it" and add some spaces in the lines, I get a nullpointer and the program ends.
Any help will be appreciated, thank you.
This is just a partial answer - at the very least your program is skipping every other line:
while ((read = in.readLine()) != null)
will read a line from the file. The line is immediately discarded because the immediately following statement:
read = in.readLine();
reads and processes the next line from the file.
(also, 'splited' should be 'splitted' along with numerous other spelling mistakes but they're not really affecting your program, just it's readability :-))

Reading a wordpad file with 3 columns in 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");
}
}

Read each line in a text file for strings, doubles, and ints an place them in different arrays

this is my first question here so I hope I'm doing this right. I have a programming project that needs to read each line of a tab delimited text file and extract a string, double values, and int values. I'm trying to place these into separate arrays so that I can use them as parameters. This is what I have so far(aside from my methods):
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Scanner;
public class LoanDriver {
public static void main(String[] args)
{
String[] stringData = new String[9];
Scanner strings = null;
try
{
FileReader read = new FileReader("amounts.txt");//Read text file.
strings = new Scanner(read);
String skip = strings.nextLine();//Skip the first line by storing it in an uncalled variable
strings.useDelimiter("\t *");//Tab delimited
}
catch (FileNotFoundException error)
{}
while (strings.hasNext())
{
String readLine = strings.next();
stringData = readLine.split("\t");
}
}}
If I try to get the [0] value, it skips all the way to the bottom of the file and returns that value, so it works to some extent, but not from the top like it should. Also, I can't incorporate arrays into it because I always get an error that String[] and String is a type mismatch.
Instead of using delimiter, try reading the file line by line using Scanner.nextLine and split each new line you read using String.split ("\t" as argument).
try {
FileReader read = new FileReader("amounts.txt");//Read text file.
strings = new Scanner(read);
String skip = strings.nextLine();//Skip the first line by storing it in an uncalled variable
}
catch (FileNotFoundException error) { }
String line;
while ((line = strings.nextLine()) != null) {
String[] parts = line.split("\t");
//...
}
You are getting the last value in the file when you grab stringData[0] because you overwrite stringData each time you go through the while loop. So the last value is the only one present in the array at the end. Try this instead:
List<String> values = new ArrayList<String>();
while (strings.hasNext()) {
values.add(strings.next());
}
stringData = values.toArray(new String[values.size()]);

Categories