How to read from inputFileStream and split each line - java

I have to read from input file txtfile that look like mark;1001;3;4 there is a ';' between each variable. I know how to read it if it's in separate lines, but I can't read it if its in the same line.
This is how I start:
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.nio.Buffer;
public class Try {
public static void main(String[] args) {
String Name;
int ID;
Double quiz1 , quiz2;
try {
FileInputStream fileIN = new FileInputStream("input.txt");
InputStreamReader inputST =new InputStreamReader(fileIN);
BufferedReader bufferRe = new BufferedReader(inputST);
String line;
while ((line = bufferRe.readLine()) != null) {
// I tried many things, but nothing worked for me.
// How could I use split here?
}
} catch (IOException e) {
System.out.println("input is not found ");
}
}
}

Using split is the way to go...
while ( ( line = bufferRe.readLine())!= null) {
for (String splitVal : line.split(";") {
//Do whatever you need to with the splitVal value.
//In you example it iterate 4 times with the values mark 1001 3 4
}
}

The simplest solution, which also works when you want things to work across newlines, is to use a Scanner with ; as its delimiter:
Scanner s = new Scanner(bufferRe);
s.useDelimiter(";");
while (s.hasNext()) {
System.out.println(s.next());
}
-->
mark
1001
3
4
This also allows you to use Scanner methods to eg. easily parse integers.

Just use split method inside loop to get all your data in array.
String[] splited = line.split(";");

while ((line = bufferRe.readLine()) != null) {
for (String retval : line.split(";", 2)) {
System.out.println(retval);
}
}
Output:
mark
1001;3;4

There is one more aproach using StreamTokenizer
try {
FileInputStream fis = new FileInputStream("input.txt");
Reader r = new BufferedReader(new InputStreamReader(fis));
StreamTokenizer st = new StreamTokenizer(r);
List<String> words = new ArrayList<>();
List<Integer> numbers = new ArrayList<>();
// print the stream tokens
boolean eof = false;
do {
int token = st.nextToken();
switch (token) {
case StreamTokenizer.TT_EOF:
System.out.println("End of File encountered.");
eof = true;
break;
case StreamTokenizer.TT_EOL:
System.out.println("End of Line encountered.");
break;
case StreamTokenizer.TT_WORD:
words.add(st.sval);
break;
case StreamTokenizer.TT_NUMBER:
numbers.add((int)st.nval);
break;
default:
System.out.println((char) token + " encountered.");
if (token == '!') {
eof = true;
}
}
} while (!eof);
} catch (IOException e) {
e.printStackTrace();
System.out.println("input is not found ");
}

Related

Indexing through an array to return any specific value in java

So, I have created code which is reading a CSV file line by line, then splitting each line into their individual values then putting this into an array, but i am stuck on trying the index a value from this array I have created, I will attach the CSV file and also my code, and lets say for example how would I access the value at [3,4], which should be Andorra, and [6,6] which should be 17?
CSV FILE:
Date,iso3,Continent,CountryName,lat,lon,CumulativePositive,CumulativeDeceased,CumulativeRecovered,CurrentlyPositive,Hospitalized,IntensiveCare,NUTS
31/1/2021,AFG,AS,Afghanistan,33.930445,67.678945,55023,2400,,52623,,,AF
31/1/2021,ALB,EU,Albania,41.156986,20.181222,78127,1380,47424,29323,324,19,AL
31/1/2021,DZA,AF,Algeria,28.026875,1.65284,107122,2888,,104234,,,DZ
31/1/2021,AND,EU,Andorra,42.542268,1.596865,9937,101,,9836,44,,AD
31/1/2021,AGO,AF,Angola,-11.209451,17.880669,19782,464,,19318,,,AO
31/1/2021,AIA,NA,Anguilla,18.225119,-63.07213,17,0,,17,,,AI
31/1/2021,ATG,NA,Antigua and Barbuda,17.363183,-61.789423,218,7,,211,,,AG
31/1/2021,ARG,SA,Argentina,-38.421295,-63.587403,1915362,47775,,1867587,,,AR
31/1/2021,ARM,AS,Armenia,40.066181,45.111108,167026,3080,,163946,,,AM
31/1/2021,ABW,NA,Aruba,12.517713,-69.965112,6858,58,,6800,,,AW
31/1/2021,AUS,OC,Australia,-26.853388,133.275154,28806,909,,27897,,,AU
31/1/2021,AUT,EU,Austria,47.697542,13.349319,411921,7850,383158,21058,1387,297,AT
31/1/2021,AZE,AS,Azerbaijan,40.147396,47.572098,229935,3119,,226816,,,AZ
31/1/2021,BHS,NA,Bahamas,24.885993,-76.709892,8174,176,,7998,,,BS
31/1/2021,BHR,AS,Bahrain,26.039722,50.559306,102626,372,,102254,,,BH
31/1/2021,BGD,AS,Bangladesh,23.68764,90.351002,535139,8127,,527012,,,BD
31/1/2021,BRB,NA,Barbados,13.18355,-59.534649,1498,12,,1486,,,BB
31/1/2021,BLR,EU,Belarus,53.711111,27.973847,248336,1718,,246618,,,BY
31/1/2021,BEL,EU,Belgium,50.499527,4.475402,711417,21118,,690299,1788,315,BE
31/1/2021,BLZ,NA,Belize,17.192929,-88.5009,11877,301,,11576,,,BZ
31/1/2021,BEN,AF,Benin,9.322048,2.313138,3786,48,,3738,,,BJ
31/1/2021,BMU,NA,Bermuda,32.320236,-64.774022,691,12,,679,,,BM
31/1/2021,BTN,AS,Bhutan,27.515709,90.442455,859,1,,858,,,BT
31/1/2021,BWA,AF,Botswana,-22.344029,24.680158,21293,134,,21159,,,BW
31/1/2021,BRA,SA,Brazil,-14.242915,-53.189267,9118513,222666,,8895847,,,BR
31/1/2021,VGB,NA,British Virgin Islands,18.573601,-64.492065,141,1,,140,,,VG
CODE:
public static String readFile(String file) {
FileInputStream fileStream = null;
InputStreamReader isr;
BufferedReader bufRdr;
int lineNum;
String line = null;
try {
fileStream = new FileInputStream(file);
isr = new InputStreamReader(fileStream);
bufRdr = new BufferedReader(isr);
lineNum = 0;
line = bufRdr.readLine();
while ((line != null) && lineNum < 27) {
lineNum++;
System.out.println(line);
line = bufRdr.readLine();
}
fileStream.close();
}
catch (IOException e) {
if (fileStream != null) {
try {
fileStream.close();
}
catch (IOException ex2) {
}
}
System.out.println("Error: " + e.getMessage());
}
return line;
}
private static void processLine(String line) {
String[] splitLine;
splitLine = line.split(",");
int lineLength = splitLine.length;
for (int i = 0; i < lineLength; i++) {
System.out.print(splitLine[i] + " ");
}
System.out.println("");
}
You need to create a 2D array in readFile. As the file is read, and and each line is split by processLine, insert the array into the 2D array. The method readFile at the end returns the 2D array. Make processLine to return a string array and have it return the result of the split.
I marked where I made changes to your code.
import java.io.*;
public class Main
{
public static void main(String[] args){
String[][] data = readFile("data.txt");
System.out.println(data[3][4]);
System.out.println(data[6][6]);
}
public static String[][] readFile(String file) { //<<< changed
FileInputStream fileStream = null;
InputStreamReader isr;
BufferedReader bufRdr;
int lineNum;
String line = null;
String[][] data = new String[28][]; //<<< added
try {
fileStream = new FileInputStream(file);
isr = new InputStreamReader(fileStream);
bufRdr = new BufferedReader(isr);
lineNum = 0;
line = bufRdr.readLine();
while (lineNum < 27) { // <<< changed
System.out.println(line);
line = bufRdr.readLine();
if (line == null) break; // <<< added
data[lineNum++] = processLine(line); // <<< added
}
fileStream.close();
}
catch (IOException e) {
if (fileStream != null) {
try {
fileStream.close();
}
catch (IOException ex2) {
}
}
System.out.println("Error: " + e.getMessage());
}
return data; //added
}
private static String[] processLine(String line) { //<< changed
String[] splitLine;
splitLine = line.split(",");
int lineLength = splitLine.length;
for (int i = 0; i < lineLength; i++) {
System.out.print(splitLine[i] + " ");
}
System.out.println("");
return splitLine; // <<< added
}
}
You can do it quite simply using the stream API.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class CsvTest0 {
public static void main(String[] args) {
Path path = Paths.get("geografy.csv");
try (Stream<String> lines = Files.lines(path)) {
String[][] arr = lines.skip(1L)
.limit(27L)
.map(l -> l.split(","))
.collect(Collectors.toList())
.toArray(new String[][]{});
System.out.println(arr[3][3]);
System.out.println(arr[5][6]);
}
catch (IOException xIo) {
xIo.printStackTrace();
}
}
}
However, regarding the code in your question, below is a fixed version followed by notes and explanations.
import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class CsvTest1 {
public static String[][] readFile(String file) throws IOException {
Path path = Paths.get(file);
String[][] arr = new String[27][];
int lineNum;
String line = null;
try (BufferedReader bufRdr = Files.newBufferedReader(path)) {
lineNum = 0;
line = bufRdr.readLine(); // Ignore first line of file since it contains headings only.
line = bufRdr.readLine();
while ((line != null) && lineNum < 27) {
arr[lineNum++] = processLine(line);
line = bufRdr.readLine();
}
}
return arr;
}
private static String[] processLine(String line) {
return line.split(",");
}
public static void main(String[] args) {
try {
String[][] arr = readFile("geografy.csv");
System.out.println(arr[3][3]);
System.out.println(arr[5][6]);
}
catch (IOException x) {
x.printStackTrace();
}
}
}
Note that the below is not in any particular order. I wrote them as they came to me.
No need for FileInputStream and InputStreamReader in order to create BufferedReader. Use Files class instead.
Close files in a finally block and not in a catch block. Hence use try-with-resources.
I believe better to propagate the exception to the calling method, i.e. method main in this case. I also believe that, unless you can safely ignore the exception, it is always beneficial to print the stack trace.
You don't want to process the first line of the file.
You appear to have your array indexes mixed up. According to sample data, Andorra is row 3 and column 3 (not column 4). Also, 17 is at [5][6] and not [6][6].
Two-dimensional arrays in java can be declared with only one dimension indicated. Since you only want first 27 lines of file, you know how many rows will be in the 2D array.

reading a specific information in file

I want to read this file using Scanner, but not all the information, only the things after semicolon like 10, warrior, John Smith and so on.
currhp: 10
type: Warrior
name: John Smith
items:
Stick,1,2,10,5
gold: 10
type: Wizard
I tried to solve it but i couldn't.
Scanner infile;
Scanner inp = new Scanner(System.in);
try {
infile = new Scanner(new File("player_save.txt"));
} catch (FileNotFoundException o) {
System.out.println(o); return; }
while (infile.hasNextLine()) {
System.out.println(infile.nextLine());
}
You need to open file, read line by line and then split each line and use the chunk of the line that you wish to do further processing on it.
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class ReadFile{
public static void main(String[] args) throws IOException {
//fix the URL to where your file is located.
try (BufferedReader br = new BufferedReader(new FileReader("C:\\player_save.txt"))) {
String line;
while ((line = br.readLine()) != null) {
if(line.length() > 0) {
if(line.contains(":")) {
System.out.println("Before colon >> " + line.split(":")[0]);
} else {
//no column found taking the whole line
System.out.println("whole line having no coln: " + line);
}
}
}
} catch(FileNotFoundException fnfe) {
//Handle scenario where the file does not exist
} catch(IOException ie) {
//Handle other File I/O exceptions here
}
}
}
You can do something like this -
List<String> list= new ArrayList<>();
try(
Scanner scan= new Scanner(new BufferedReader(new FileReader("//your filepath")));
){
while(scan.hasNextLine()){
String s=scan.nextLine();
if(s.contains(":")){
String arr[]=s.split(":");
list.add(arr[1].trim());
}
}
}
catch(Exception e){
System.out.println(e.getMessage());
}
for(String str:list){
System.out.println(str);
}

Finding String in a list of text files in a directory Java ..want to locate line number.

Hi I am trying to add a functionality where I can also keep track of the line number of the string that is found. Not sure where and how to implement this in the following code. Keep in mind the files that I am looking into are 50mb in size.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class scanFiles {
private static void scanFiles(String folderPath, String searchString) throws FileNotFoundException, IOException {
File folder = new File(folderPath);
if (folder.isDirectory()) {
for (File file : folder.listFiles()) {
if (!file.isDirectory()) {
BufferedReader br = new BufferedReader(new FileReader(file));
String content = "";
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
content = sb.toString();
} finally {
br.close();
}
if (content.contains(searchString)) {
System.out.println("File " + file.getName() + " contains searchString " + searchString + "!");
}
}
}
} else {
System.out.println("Not a Directory!");
}
}
public static void main(String args[]) throws FileNotFoundException, IOException{
scanFiles(new File("C://Users//FarmaniA//Documents//COB NAK Messages").getAbsolutePath(),"15:09:07,803");
}
}
Search for the text as you loop over each line of the file while reading. Keep a record of the line numbers where the String is found. For example:
List<Integer> lineNumbers = new ArrayList<Integer>();
int lineNumber = 0;
while ( line != null ){
lineNumber++;
if ( line.indexOf(searchString) != -1 ){
lineNumbers.add(lineNumber);
}
line = br.readLine();
}
if ( lineNumbers.size() > 0 ){
//do something with them
}
Depending upon context, you may also wish to do a case insensitive search by changing the search String and each line to a particular case (uppercase/lowercase).

Reverse lines in ArrayList Java

I'm working on a Java program in which I must read the contents of a file and then print each lines reverse. For example the text:
Public Class Helloprinter
Public static void
would print the following after running my reverse program:
retnirPolleh ssalc cilbup
diov citats cilbup
Here's what I got so far:
public static void main(String[] args) throws FileNotFoundException {
// Prompt for the input and output file names
ArrayList<String> list = new ArrayList<String>();
//String reverse = "";
Scanner console = new Scanner(System.in);
System.out.print("Input file: ");
String inputFileName = console.next();
System.out.print("Output file: ");
String outputFileName = console.next();
// Construct the Scanner and PrintWriter objects for reading and writing
File inputFile = new File(inputFileName);
Scanner in = new Scanner(inputFile);
PrintWriter out = new PrintWriter(outputFileName);
String aString = "";
while(in.hasNextLine())
{
String line = in.nextLine();
list.add(line);
}
in.close();
for(int i = 0; i <list.size(); i++)
{
aString = list.get(i);
aString = new StringBuffer(aString).reverse().toString();
out.printf("%s", " " + aString);
}
out.close();
}
}
EDIT:
With Robert's posting it helped put me in the right direction. The problem is that with that is that it doesn't keep the lines.
Public Class Helloprinter
Public static void
becomes after running my program:
retnirPolleh ssalc cilbup diov citats cilbup
it needs to keep the line layout the same. so it should be:
retnirPolleh ssalc cilbup
diov citats cilbup
Your problem is in the line
out.printf("%s", " " + aString);
This doesn't output a newline. I'm also not sure why you are sticking a space in there.
It should be either:
out.println( aString );
Or
out.printf("%s%n", aString);
In your last loop why don't you just iterate through the list backwards? So:
for(int i = 0; i <list.size(); i++)
Becomes:
for(int i = list.size() - 1; i >=0; i--)
It seems like you already know how to read a file, so then call this method for each line.
Note, this is recursion and it's probably not the most efficient but it's simple and it does what you want.
public String reverseString(final String s) {
if (s.length() == 0)
return s;
// move chahctrachter at current position and then put it at the end of the string.
return reverseString(s.substring(1)) + s.charAt(0);
}
Just use a string builder. You were on the right trail. Probably just needed a little help. There is no "one way" to do anything, but you could try something like this:
Note: Here is my output: retnirPolleh ssalc cilbup diov citats cilbup
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Scanner;
public class Reverse {
public static void main(String[] args) {
ArrayList<String> myReverseList = null;
System.out.println("Input file: \n");
Scanner input = new Scanner(System.in);
String fileName = input.nextLine();
System.out.println("Output file: \n");
String outputFileName = input.nextLine();
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(fileName));
String text = null;
myReverseList = new ArrayList<String>();
StringBuilder sb = null;
try {
while ((text = br.readLine()) != null) {
sb = new StringBuilder();
for (int i = text.length() - 1; i >= 0; i--) {
sb.append(text.charAt(i));
}
myReverseList.add(sb.toString());
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Writer writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(outputFileName), "utf-8"));
for (String s : myReverseList) {
writer.write("" + s + "\n");
}
} catch (IOException ex) {
// report
} finally {
try {
writer.close();
} catch (Exception ex) {
}
}
}
}

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