Java - Reading a line from a file containing text and number - java

I'm just trying to do an exercise where I have to read a particular file called test.txt in the following format:
Sampletest 4
What I want to do is that I want to store the text part in one variable and the number in another. I am still a beginner so I had to google quite a bit to find something that would at-least work, here what I got so far.
public static void main(String[] args) throws Exception{
try {
FileReader fr = new FileReader("test.txt");
BufferedReader br = new BufferedReader(fr);
String str;
while((str = br.readLine()) != null) {
System.out.println(str);
}
br.close();
} catch(IOException e) {
System.out.println("File not found");
}

Use a Scanner, which makes reading your file way easier than DIY code:
try (Scanner scanner = new Scanner(new FileInputStream("test.txt"));) {
while(scanner.hasNextLine()) {
String name = scanner.next();
int number = scanner.nextInt();
scanner.nextLine(); // clears newlines from the buffer
System.out.println(str + " and " + number);
}
} catch(IOException e) {
System.out.println("File not found");
}
Note the use of the try-with-resources syntax, which closes the scanner automatically when the try is exited, usable because Scanner implements Closeable.

You just need:
String[] parts = str.split(" ");
And parts[0] is the text (sampletest)
And parts[1] is the number 4

It seems like you are reading the whole file content (from test.txt file) line by line, so you need two separate List objects to store the numeric and non-numeric lines as shown below:
String str;
List<Integer> numericValues = new ArrayList<>();//stores numeric lines
List<String> nonNumericValues = new ArrayList<>();//stores non-numeric lines
while((str = br.readLine()) != null) {
if(str.matches("\\d+")) {//check line is numeric
numericValues.add(str);//store to numericList
} else {
nonNumericValues.add(str);//store to nonNumericValues List
}
}

If you are sure the format is always for each line in the file.
String str;
List<Integer> intvalues = new ArrayList<Integer>();
List<String> charvalues = new ArrayList<String>();
try{
BufferedReader br = new BufferedReader(new FileReader("test.txt"));
while((str = br.readLine()) != null) {
String[] parts = str.split(" ");
charvalues.add(parts[0]);
intvalues.add(new Integer(parts[0]));
}
}catch(IOException ioer) {
ioer.printStackTrace();
}

You can use java utilities Files#lines()
Then you can do something like this. Use String#split() to parse each line with a regular expression, in this example i use a comma.
public static void main(String[] args) throws IOException {
try (Stream<String> lines = Files.lines(Paths.get("yourPath"))) {
lines.map(Representation::new).forEach(System.out::println);
}
}
static class Representation{
final String stringPart;
final Integer intPart;
Representation(String line){
String[] splitted = line.split(",");
this.stringPart = splitted[0];
this.intPart = Integer.parseInt(splitted[1]);
}
}

Related

Reading file (using FileReader) and splitting line into two strings in Java

import java.io.*;
public class ReadFile {
public static void read(File f) throws IOException {
//String delimiters = ".";
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
String line;
//int numberOfLines = 0;
while ((line = br.readLine()) != null) {
String[] tokens = line.split("\\.", 2);
String p1 = tokens[0];
String p2 = tokens[1];
System.out.println(p1);
System.out.println(p2);
//numberOfLines++;
}
//System.out.println("Numebr of lines in file: " + numberOfLines);
br.close();
fr.close();
}
public static void main(String[] args) {
File f = new File("F:\\Dictionary.txt");
try {
read(f);
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
I have a problem in which I'm using a Dictionary as a text file and I want to read the lines (of dictionary file) and then split it up so that I can store the "words" and their "meanings" into different array indexes. This String[] tokens = line.split("\\.", 2); to read and split at only the first "." (so that words proceeding after "." will be splitted!). I seem to having an error of ArrayIndexOutOfBound and I don't know why. I wantString p1 = tokens[0]; to store the words and `String p12 = tokens1; the meanings of the words. How can I do it?
https://drive.google.com/open?id=0ByAbzVqaUg0BSFp5NXNHOGhuOFk Link for Dictionary.
Your dictionary file is not what your program expects it to be.
There are lines with single letters (like the very first line containing single letter A). Then you have plenty of empty lines.
To make your processing more robust make these modifications to your parsing loop:
while ((line = br.readLine()) != null) {
//skip empty lines
if (line.length() <= 1) {
continue;
}
try {
String[] tokens = line.split("\\.", 2);
String p1 = tokens[0];
String p2 = tokens[1];
System.out.println(p1);
System.out.println(p2);
} catch (IndexOutOfBoundsException e) {
//catch index out of bounds and see why
System.out.println("PROBLEM with line: " + line);
}
}

Omit elements in array based on the first word

What I'm looking to do here is process a log file, in my case it's squid's access.log. I want to have my program take a look at the first 'word' in the file, which is the time in Unix format of when the URL was accessed. In other parts of the program, I designed a time class, which gets the time the program was last run in Unix time, and I want to compare this time to the first word in the file, which happens to be a Unix time.
My initial thinking on how to do this is that I process the file, store it in array, then based on the first word in the file, omit the lines by removing it from the array that the processed file is in, and put it in another array
Here's what I've got so far. I'm pretty sure that I'm close, but this is the first time that I've done file processing, so I don't exactly know what I'm doing here.
private void readFile(File file) throws FileNotFoundException, IOException{
String[] lines = new String[getLineCount(file)];
Long unixTime = time.getUnixLastRun();
String[] removedTime = new String[getLineCount(file)];
try(BufferedReader br = new BufferedReader(new FileReader(file))) {
int i = 0;
for(String line; (line = br.readLine()) != null; i++) {
lines[i] = line;
}
}
for(String arr: lines){
System.out.println(arr);
}
}
private void readFile(File file) {
List<String> lines = new ArrayList<String>();
List<String> firstWord = new ArrayList<String>();
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
// Adds the entire first line
lines.add(sCurrentLine);
// Adds the first word
firstWord.add(sCurrentLine.split(" ")[0]);
}
} catch (IOException e) {
e.printStackTrace();
}
}
If you want you can use your arrays.
private void readFile(File file) throws FileNotFoundException, IOException {
String[] lines = new String[getLineCount(file)];
Long unixTime = time.getUnixLastRun();
String[] removedTime = new String[getLineCount(file)];
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
int i = 0;
for (String line; (line = br.readLine()) != null; i++) {
lines[i] = line;
}
}
ArrayList<String> logsToBeUsed = new ArrayList<String>();
for (String arr : lines) {
//Gets the first word from the line and compares it with the current unix time, if it is >= unix time
//then we add it to the list of Strings to be used
try{
if(Long.parseLong(getFirstWord(arr)) >= unixTime){
logsToBeUsed.add(arr);
}
}catch(NumberFormatException nfe){
//Means the first word was not a float, do something here
}
}
}
private String getFirstWord(String text) {
if (text.indexOf(' ') > -1) {
return text.substring(0, text.indexOf(' '));
} else {
return text;
}
}
This is the answer according to the code you posted. This can be done more efficiently as you can use an ArrayList to store the lines from the file rather than first reading the line number getLineCount(file) as you open the file twice. And in the for loop you are declaring the String object again and again.

Adding each line from an input file into an array

I need to add the contents of every line (single word) of an user input text file into a separate element in an array.
*I know an ArrayList is a better data structure for this problem but I am limited to using only an array.
Here is my code:
public static void main(String[] args) throws FileNotFoundException {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a file name: ");
System.out.flush();
String filename = scanner.nextLine();
File file = new File(filename);
FileReader reader = new FileReader(file);
try (BufferedReader buffReader = new BufferedReader(reader)) {
String line;
int i=0;
String[] words = new String[10];
while((line = buffReader.readLine()) != null) {
words[i]=buffReader.readLine();
System.out.println(words[i]);
i++;
}
}
catch(IOException e){
System.out.println(e);
}
}
The input file is simply:
Pans
Pots
opt
sit
it's
snap
Program output is below. It seems to be skipping every other line.
Pots
sit
snap
You are reading two lines per while loop iteration, one in the while condition, and the other in the first line of the loop body. The result is that each iteration consumes two lines, and only the second of the two is printed.
Eliminate the second call in the loop body, so that you have one iteration of the loop (and one print statement) per line.
Change the while loop as shown below. If while loop condition check, you are reading the line then again reading the line in first line in your while loop. So you are reading two lines and printing only one line.
while((line = buffReader.readLine()) != null) {
System.out.println(line );
i++;
}
while((line = buffReader.readLine()) != null)
That line read and consumed the first input line and that is why you are not seeing Pans and the even indexed inputs.
Can you use an ArrayList than just convert it to an Array using the toArray method? What are your limitations and why?
public static void main(String[] args) throws FileNotFoundException {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a file name: ");
System.out.flush();
String filename = scanner.nextLine();
File file = new File(filename);
FileReader reader = new FileReader(file);
try (BufferedReader buffReader = new BufferedReader(reader)) {
String line;
int i=0;
String[] words = new String[10];
//modify line = buffReader.readLine()
while((words[i]=buffReader.readLine()) != null) {
//modify //words[i]=buffReader.readLine();
//words[i]=buffReader.readLine();
System.out.println(words[i]);
i++;
}
}
catch(IOException e){
System.out.println(e);
}
}

Best way to read data from a file [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Best way to read a text file
In Java I can open a text file like this:
BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
My question is, how do you read from the following file? The first line is a number (830) representing number of words, and the following lines contain the words.
830
cooking
English
weather
.
.
I want to read the words into a string array. But how do I read the data first?
You're on the right track; I would treat the first line as a special case by parsing it as an integer (see Integer#parseInt(String)) then reading the words as individual lines:
BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
String numLinesStr = reader.readLine();
if (numLinesStr == null) throw new Exception("invalid file format");
List<String> lines = new ArrayList<String>();
int numLines = Integer.parseInt(numLinesStr);
for (int i=0; i<numLines; i++) {
lines.add(reader.readLine());
}
Unless you have some special reason, it's not necessary to keep track of how many lines the file contain. Just use something like this:
BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
String line;
while ((line = reader.readLine()) != null) {
// ...
}
If you're working with Java version greater than 1.5, you can also use the Scanner class:
Scanner sc = new Scanner(new File("someTextFile.txt"));
List<String> words = new ArrayList<String>();
int lines = sc.nextInt();
for(int i = 1; i <= lines; i++) {
words.add(sc.nextLine());
}
String[] w = words.toArray(new String[]{});
Try the class java.io.BufferedReader, created on a java.io.FileReader.
This object has the method readLine, which will read the next line from the file:
try
{
java.io.BufferedReader in =
new java.io.BufferedReader(new java.io.FileReader("filename.txt"));
String str;
while((str = in.readLine()) != null)
{
...
}
}
catch(java.io.IOException ex)
{
}
You could use reflection and do this dynamically:
public static void read() {
try {
BufferedReader reader = new BufferedReader(new FileReader(
"filename.txt"));
String line = reader.readLine();
while (line != null) {
if (Integer.class.isAssignableFrom(line.getClass())) {
int number = Integer.parseInt(line);
System.out.println(number);
} else {
String word = line;
System.out.println(word);
}
line = reader.readLine();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

Java file read problem

I have a java problem. I am trying to read a txt file which has a variable number of integers per line, and for each line I need to sum every second integer! I am using scanner to read integers, but can't work out when a line is done. Can anyone help pls?
have a look at the BufferedReader class for reading a textfile and at the StringTokenizer class for splitting each line into strings.
String input;
BufferedReader br = new BufferedReader(new FileReader("foo.txt"));
while ((input = br.readLine()) != null) {
input = input.trim();
StringTokenizer str = new StringTokenizer(input);
String text = str.nextToken(); //get your integers from this string
}
If I were you, I'd probably use FileUtils class from Apache Commons IO. The method readLines(File file) returns a List of Strings, one for each line. Then you can simply handle one line at a time.
Something like this:
File file = new File("test.txt");
List<String> lines = FileUtils.readLines(file);
for (String line : lines) {
// handle one line
}
(Unfortunately Commons IO doesn't support generics, so the there would be an unchecked assignment warning when assigning to List<String>. To remedy that use either #SuppressWarnings, or just an untyped List and casting to Strings.)
This is, perhaps, an example of a situation where one can apply "know and use the libraries" and skip writing some lower-level boilerplate code altogether.
or scrape from commons the essentials to both learn good technique and skip the jar:
import java.io.*;
import java.util.*;
class Test
{
public static void main(final String[] args)
{
File file = new File("Test.java");
BufferedReader buffreader = null;
String line = "";
ArrayList<String> list = new ArrayList<String>();
try
{
buffreader = new BufferedReader( new FileReader(file) );
line = buffreader.readLine();
while (line != null)
{
line = buffreader.readLine();
//do something with line or:
list.add(line);
}
} catch (IOException ioe)
{
// ignore
} finally
{
try
{
if (buffreader != null)
{
buffreader.close();
}
} catch (IOException ioe)
{
// ignore
}
}
//do something with list
for (String text : list)
{
// handle one line
System.out.println(text);
}
}
}
This is the solution that I would use.
import java.util.ArrayList;
import java.util.Scanner;
public class Solution1 {
public static void main(String[] args) throws IOException{
String nameFile;
File file;
Scanner keyboard = new Scanner(System.in);
int total = 0;
System.out.println("What is the name of the file");
nameFile = keyboard.nextLine();
file = new File(nameFile);
if(!file.exists()){
System.out.println("File does not exit");
System.exit(0);
}
Scanner reader = new Scanner(file);
while(reader.hasNext()){
String fileData = reader.nextLine();
for(int i = 0; i < fileData.length(); i++){
if(Character.isDigit(fileData.charAt(i))){
total = total + Integer.parseInt(fileData.charAt(i)+"");
}
}
System.out.println(total + " \n");
}
}
}

Categories

Resources