Using Scanner to read Strings in Java - java

I'm trying to read a file called "CityData.txt" that just has a list of city names in it, one on each line. I've been using scanner in the past to read Strings from a file, and am using it to read ints from another file in this same program, however it doesn't seem to be reading anything from the file.
int counter2 = 0;
File strFile = new File("CityData.txt");
Scanner strScanner = new Scanner(strFile);
Scanner strCountScanner = new Scanner(strFile);
while ((strScanner.hasNext() == true)) {
System.out.println(strScanner.nextLine());
counter2++;
}
System.out.println("This is counter2: " + counter2);
String[] array2 = new String[counter2];
while ((strCountScanner.hasNext() == true)) {
for (int i = 0; i < counter2; i++) {
array2[i] = strCountScanner.nextLine();
}
}
Ideally, counter2 will tell me how many cities are in the file, and I'll then populate array2 with them. However, counter2 remains at 0 after the program has been run. I've been fiddling with this for a while, and am hoping that maybe I've just missed something silly.
Thanks

You are trying to add cities to an array?
public static void readText throws FileNotFoundException {
ArrayList lines = new ArrayList();
Scanner scan = new Scanner(new File("CityData.txt"));
while(scan.hasNextLine()){
String line = scan.nextLine();
lines.add(line);
}
}
or a stream in 8
Stream <String> lines = Files.lines(Paths.get("c:\\demo.txt"));
lines.forEach(System.out::println);
lines.close();

Ideally I would avoid two loops and just use an ArrayList for this purpose. This can give you count as well as the flexibility to make the array more dynamic. Also I would enclose Scanner in try with resources block as it closes the resource itself. Here is the code for reference.
File strFile = new File("CityData.txt");
try (Scanner strScanner = new Scanner(strFile)) {
ArrayList<String> arrayList = new ArrayList<>();
while (strScanner.hasNext()) {
arrayList.add(strScanner.nextLine());
}
System.out.println("number of cities is " + arrayList.size());
System.out.println("cities are " + arrayList);
}catch (Exception e){
e.printStackTrace();
}

Since you are reading in string, using hasNextLine() will be more appropriate. You can try the code below, it should work as intended. HTH.
int counter2 = 0;
File strFile = new File("CityData.txt");
Scanner strScanner = new Scanner(strFile);
Scanner strCountScanner = new Scanner(strFile);
while((strScanner.hasNextLine() == true)) {
System.out.println(strScanner.nextLine());
counter2++;
}
System.out.println("This is counter2: " + counter2);
String[] array2 = new String[counter2];
while((strCountScanner.hasNextLine() == true)) {
for (int i = 0; i < counter2; i++) {
array2[i] = strCountScanner.nextLine();
}
}

Related

How to get data from a CSV file and place it in a list

I want to read data from a CSV file in Java and then put this data into a list. The data in the CSV is put into rows which looks like:
Data, 32, 4.3
Month, May2, May 5
The code I have currently only prints the [32].
ArrayList<String> myList = new ArrayList<String>();
Scanner scanner = new Scanner(new File("\\C:\\Users\\Book1.csv\\"));
scanner.useDelimiter(",");
while(scanner.hasNext()){
myList.add(scanner.next());
for (int i = 0; i <= myList.size(); i++) {
System.out.println(myList.toString());
}
scanner.close();
}
Maybe this code can help you, maybe this code is different from yours, you use arrayList while I use regular array.
Example of the data:
Farhan,3.84,4,72
Rajab,2.98,4,72
Agil,2.72,4,72
Alpin,3.11,4,73
Mono,3,6,118 K
imel,3.97,7,132
Rano,2.12,6,110
Kukuh,4,1,22
Placing data on each row in a csv file separated by commas into the array of each index
int tmp = 0;
String read;
Mahasiswa[] mhs = new Mahasiswa[100];
BufferedWriter outs;
BufferedReader ins;
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
Scanner input = new Scanner(System.in);
try {
ins = new BufferedReader(new FileReader("src/file.csv"));
tmp = 0;
while ((read = ins.readLine()) != null) {
String[] siswa = read.split(",");
mhs[tmp] = new Mahasiswa();
mhs[tmp].nama = siswa[0];
mhs[tmp].ipk = Float.parseFloat(siswa[1]);
mhs[tmp].sem = Integer.parseInt(siswa[2]);
mhs[tmp].sks = Integer.parseInt(siswa[3]);
tmp++;
i++;
}
ins.close();
} catch (IOException e) {
System.out.println("Terdapat Masalah: " + e);
}
Print the array data
tmp = 0;
while (tmp < i) {
System.out.println(mhs[tmp].nama + "\t\t" +
mhs[tmp].ipk + "\t\t" +
mhs[tmp].sem + "\t\t" +
mhs[tmp].sks);
tmp++;
}
ArrayList<String> myList = new ArrayList<String>();
try (Scanner scanner = new Scanner(new File("C:\\Users\\Book1.csv"))) {
//here at your code there are backslashes at front and end of the path that was the
//main reason you are not able to read csv file
scanner.useDelimiter(",");
while (scanner.hasNext()) {
myList.add(scanner.next());
}
for (int i = 0; i < myList.size(); i++) { //remember index is always equal to "length - 1"
System.out.println(myList);
}
} catch (Exception e) {
e.printStackTrace();
}
you also did not handle the FileNotFoundException
Hope this helps:)

Take values from a text file and put them in a array

For now in my program i am using hard-coded values, but i want it so that the user can use any text file and get the same result.
import java.io.IOException;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.File;
public class a1_12177903
{
public static void main(String [] args) throws IOException
{
if (args[0] == null)
{
System.out.println("File not found");
}
else
{
File file = new File(args[0]);
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line = "";
while (br.ready())
{
line += br.readLine();
}
String[] work = line.split(",");
double[] doubleArr = new double[work.length];
for (int i =0; i < doubleArr.length; i++)
{
doubleArr[i] = Double.parseDouble(work[i]);
}
double maxStartIndex=0;
double maxEndIndex=0;
double maxSum = 0;
double total = 0;
double maxStartIndexUntilNow = 0;
for (int currentIndex = 0; currentIndex < doubleArr.length; currentIndex++)
{
double eachArrayItem = doubleArr[currentIndex];
total += eachArrayItem;
if(total > maxSum)
{
maxSum = total;
maxStartIndex = maxStartIndexUntilNow;
maxEndIndex = currentIndex;
}
if (total < 0)
{
maxStartIndexUntilNow = currentIndex;
total = 0;
}
}
System.out.println("Max sum : "+ maxSum);
System.out.println("Max start index : "+ maxStartIndex);
System.out.println("Max end index : " +maxEndIndex);
}
}
}
I've fixed it so it takes in the name of the text file from the command line. if anyone has any ways to improve this, I'll happily accept any improvments.
You can do this with Java8 Streams, assuming each entry has it's own line
double[] doubleArr = Files.lines(pathToFile)
.mapToDouble(Double::valueOf)
.toArray();
If you were using this on production systems (rather than as an exercise) it would be worth while to create the Stream inside a Try with Resources block. This will make sure your input file is closed properly.
try(Stream<String> lines = Files.lines(path)){
doubleArr = stream.mapToDouble(Double::valueOf)
.toArray();
}
If you have a comma separated list, you will need to split them first and use a flatMap.
double[] doubleArr = Files.lines(pathToFile)
.flatMap(line->Stream.of(line.split(","))
.mapToDouble(Double::valueOf)
.toArray();
public static void main(String[] args) throws IOException {
String fileName = "";
File inputFile = new File(fileName);
BufferedReader br = new BufferedReader(new FileReader(inputFile));
// if input is in single line
StringTokenizer str = new StringTokenizer(br.readLine());
double[] intArr = new double[str.countTokens()];
for (int i = 0; i < str.countTokens(); i++) {
intArr[i] = Double.parseDouble(str.nextToken());
}
// if multiple lines in input file for a single case
String line = "";
ArrayList<Double> arryList = new ArrayList<>();
while ((line = br.readLine()) != null) {
// delimiter of your choice
for (String x : line.split(" ")) {
arryList.add(Double.parseDouble(x));
}
}
// convert arraylist to array or maybe process arrayList
}
This link may help: How to use BufferedReader. Then you will get a String containing the array.
Next you have several ways to analyze the string into an array.
Use JSONArray to parse it. For further information, search google for JSON.
Use the function split() to parse string to array. See below.
Code for way 2:
String line="10,20,50";//in fact you get this from file input.
String[] raw=line.split(",");
String[] arr=new String[raw.length];
for(int i=0;i<raw.length;++i)arr[i]=raw[i];
//now arr is what you want
Use streams if you are on JDK8. And please take care of design principles/patterns as well. It seems like a strategy/template design pattern can be applied here. I know, nobody here would ask you to focus on design guidelines.And also please take care of naming conventions. "File" as class name is not a good name.

reading text from .db file one line at a time

First of, I don't know how a.db file stores it data. If it does it in one line, or over many lines. Probably it does some difference from how to solve the problem.
the problem I'm facing is that I don't know how much data the file contains, only that it will be a date, time, and a description for x number of events in the form given below.
I have to convert the text into strings and put them in an array, but I don't know how to separate the text. When I tried I just ended up with one long string.
Can anybody help me?
01.01.2015|07:00-07:15|get up
01.01.2015|08:00|get to work
01.01.2015|08:00-16:00| work
01.01.2015|16:00-16:30| go home
what I want:
array[0] = "01.01.2015|07:00-07:15|get up"
array[1] = "01.01.2015|08:00|get to work"
array[2] = "01.01.2015|08:00-16:00| work"
array[3] = "01.01.2015|16:00-16:30| go home"
string table[] = new String [100];
void readFile(String fileName){
String read = "";
try {
x = new Scanner (new File(fileName));
}
catch (Exception e) {
}
while (x.hasNext()) {
read += x.nextLine();
}
}
Assuming here that your first code-block is in fact a copy of the file you're trying to read, you can do:
Scanner s = new Scanner(new File("file1.txt"));
List<String> lines = new LinkedList<>();
while (s.hasNextLine())
lines.add(s.nextLine());
If you really want to work with arrays and not lists, you can do
String[] table = lines.toArray(new String[lines.size()]);
after the loop.
If you're fortunate enough to work with Java 8, you can use:
List<String> lines = Files.lines(Paths.get("big.txt"))
.collect(Collectors.toList());
Again, if you really want to work with an array, you can convert the list using lines.toArray.
Since Java 8 you can use Paths.get(String first, String... more), Files.lines(Path path), and Stream.toArray():
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class SOPlayground {
public static void main(String[] args) throws Exception {
Path path = Paths.get("/tmp", "db.txt");
Object[] lines = Files.lines(path).toArray();
System.out.println(lines.length);
System.out.println(lines[0]);
System.out.println(lines[lines.length - 1]);
}
}
Output:
4
01.01.2015|07:00-07:15|get up
01.01.2015|16:00-16:30| go home
Try this solution using arrays:
code
Scanner sc = new Scanner(new File("file.txt"));
int index;
String[] arr = new String[1];
for(index = 0; sc.hasNextLine(); index++) {
arr = Arrays.copyOf(arr, index + 1);
arr[index] = sc.nextLine();
}
for(int i = 0; i<arr.length; i++) {
System.out.print(arr[i] + "\n");
}
I have used arr = Arrays.copyOf(arr, index + 1) to increase the size of the array to add next element.
Output
01.01.2015|07:00-07:15|get up
01.01.2015|08:00|get to work
01.01.2015|08:00-16:00| work
01.01.2015|16:00-16:30| go home
Well, it took me some houres. Thanx to all who lended a hand. This was what I got in the end.
int i=0;
String array [] new String [100]
try {
FileReader textFileReader= new FileReader (fileName);
BufferedReader textReader= new BufferedReader(textFileReader);
boolean continue = true;
while (continue) {
String text = textReader.readLine();
if (text != null){
array[i] = text;
i++;
}else {
continue = false;
}
}
}catch (Exception e) {}

Infile Outputting only 1 line

My outer loop to control reading the data file is not correct, can someone explain to me how to get the loop to print the entire data file and not just the first word in the data file?
public static void display() throws IOException, FileNotFoundException {
Scanner infile = new Scanner(new FileReader("G:\\DataFileDS.txt"));
StringTokenizer token = new StringTokenizer(infile.nextLine());
StringElement str = new StringElement();
while(token.hasMoreTokens()) {
str.setString(token.nextToken());
stringList.insert(str);
}
stringList.print();
int n = stringList.listSize();
for(int i = 0; i < n - 1; ++i) {
System.out.println(stringList.retrieveAt(i) + " " + stringList.retrieveAt(i+1));
}
}
I guess the while loop runs first and once it finishes, it prints the value. Then your for loop runs only once as listsize is probably one.
Try printing list size. Since I cant test this code.
It might be this way:
public static void Display()throws IOException, FileNotFoundException
{
Scanner infile = new Scanner(new FileReader("G:\\DataFileDS.txt"));
StringTokenizer token = new StringTokenizer(infile.nextLine());
StringElement str = new StringElement();
while(token.hasMoreTokens())
{
str.setString(token.nextToken());
stringList.insert(str);
int n = stringList.listSize();
for(int i=0; i<n-1; i=i+1)
{
System.out.println(stringList.retrieveAt(i) + " " + stringList.retrieveAt(i+1));
}
stringList.print();
}
}

Java Reading 2D array in from file, numbers separated by comma

This is some code that I found to help with reading in a 2D Array, but the problem I am having is this will only work when reading a list of number structured like:
73
56
30
75
80
ect..
What I want is to be able to read multiple lines that are structured like this:
1,0,1,1,0,1,0,1,0,1
1,0,0,1,0,0,0,1,0,1
1,1,0,1,0,1,0,1,1,1
I just want to essentially import each line as an array, while structuring them like an array in the text file.
Everything I have read says to use scan.usedelimiter(","); but everywhere I try to use it the program throws straight to the catch that replies "Error converting number". If anyone can help I would greatly appreciate it. I also saw some information about using split for the buffered reader, but I don't know which would be better to use/why/how.
String filename = "res/test.txt"; // Finds the file you want to test.
try{
FileReader ConnectionToFile = new FileReader(filename);
BufferedReader read = new BufferedReader(ConnectionToFile);
Scanner scan = new Scanner(read);
int[][] Spaces = new int[10][10];
int counter = 0;
try{
while(scan.hasNext() && counter < 10)
{
for(int i = 0; i < 10; i++)
{
counter = counter + 1;
for(int m = 0; m < 10; m++)
{
Spaces[i][m] = scan.nextInt();
}
}
}
for(int i = 0; i < 10; i++)
{
//Prints out Arrays to the Console, (not needed in final)
System.out.println("Array" + (i + 1) + " is: " + Spaces[i][0] + ", " + Spaces[i][1] + ", " + Spaces[i][2] + ", " + Spaces[i][3] + ", " + Spaces[i][4] + ", " + Spaces[i][5] + ", " + Spaces[i][6]+ ", " + Spaces[i][7]+ ", " + Spaces[i][8]+ ", " + Spaces[i][9]);
}
}
catch(InputMismatchException e)
{
System.out.println("Error converting number");
}
scan.close();
read.close();
}
catch (IOException e)
{
System.out.println("IO-Error open/close of file" + filename);
}
}
I provide my code here.
public static int[][] readArray(String path) throws IOException {
//1,0,1,1,0,1,0,1,0,1
int[][] result = new int[3][10];
BufferedReader reader = new BufferedReader(new FileReader(path));
String line = null;
Scanner scanner = null;
line = reader.readLine();
if(line == null) {
return result;
}
String pattern = createPattern(line);
int lineNumber = 0;
MatchResult temp = null;
while(line != null) {
scanner = new Scanner(line);
scanner.findInLine(pattern);
temp = scanner.match();
int count = temp.groupCount();
for(int i=1;i<=count;i++) {
result[lineNumber][i-1] = Integer.parseInt(temp.group(i));
}
lineNumber++;
scanner.close();
line = reader.readLine();
}
return result;
}
public static String createPattern(String line) {
char[] chars = line.toCharArray();
StringBuilder pattern = new StringBuilder();;
for(char c : chars) {
if(',' == c) {
pattern.append(',');
} else {
pattern.append("(\\d+)");
}
}
return pattern.toString();
}
The following piece of code snippet might be helpful. The basic idea is to read each line and parse out CSV. Please be advised that CSV parsing is generally hard and mostly requires specialized library (such as CSVReader). However, the issue in hand is relatively straightforward.
try {
String line = "";
int rowNumber = 0;
while(scan.hasNextLine()) {
line = scan.nextLine();
String[] elements = line.split(',');
int elementCount = 0;
for(String element : elements) {
int elementValue = Integer.parseInt(element);
spaces[rowNumber][elementCount] = elementValue;
elementCount++;
}
rowNumber++;
}
} // you know what goes afterwards
Since it is a file which is read line by line, read each line using a delimiter ",".
So Here you just create a new scanner object passing each line using delimter ","
Code looks like this, in first for loop
for(int i = 0; i < 10; i++)
{
Scanner newScan=new Scanner(scan.nextLine()).useDelimiter(",");
counter = counter + 1;
for(int m = 0; m < 10; m++)
{
Spaces[i][m] = newScan.nextInt();
}
}
Use the useDelimiter method in Scanner to set the delimiter to "," instead of the default space character.
As per the sample input given, if the next row in a 2D array begins in a new line, instead of using a ",", multiple delimiters have to be specified.
Example:
scan.useDelimiter(",|\\r\\n");
This sets the delimiter to both "," and carriage return + new line characters.
Why use a scanner for a file? You already have a BufferedReader:
FileReader fileReader = new FileReader(filename);
BufferedReader reader = new BufferedReader(fileReader);
Now you can read the file line by line. The tricky bit is you want an array of int
int[][] spaces = new int[10][10];
String line = null;
int row = 0;
while ((line = reader.readLine()) != null)
{
String[] array = line.split(",");
for (int i = 0; i < array.length; i++)
{
spaces[row][i] = Integer.parseInt(array[i]);
}
row++;
}
The other approach is using a Scanner for the individual lines:
while ((line = reader.readLine()) != null)
{
Scanner s = new Scanner(line).useDelimiter(',');
int col = 0;
while (s.hasNextInt())
{
spaces[row][col] = s.nextInt();
col++;
}
row++;
}
The other thing worth noting is that you're using an int[10][10]; this requires you to know the length of the file in advance. A List<int[]> would remove this requirement.

Categories