I'm trying to read doubles from a file that contains 100,000 doubles, arranged in lines of two doubles each separated by a space. Like this:
2.54343 5.67478
1.23414 5.43245
7.64748 4.25536
...
My code so far:
Scanner numFile = new Scanner(new File("input100K.txt").getAbsolutePath());
ArrayList<Double> list = new ArrayList<Double>();
while (numFile.hasNextLine()) {
String line = numFile.nextLine();
Scanner sc = new Scanner(line);
sc.useDelimiter(" ");
while(sc.hasNextDouble()) {
list.add(sc.nextDouble());
}
sc.close();
}
numFile.close();
System.out.println(list);
}
After this code runs, it prints to the console and empty ArrayList [], and I can't figure out why.
Removing the getAbsolutePath() from the file gives me this line:
Scanner numFile = new Scanner(new File("input100K.txt"));
but when I run the program, it is giving me a FileNotFoundException. I know the file exists, I can see it and open it.
input100K.txt is located in the src package folder along with the program. is there somewhere specific where the file must be for this to work?
EDIT: As Evgeniy Dorofeev pointed out, the file needs to be in the project folder (parent of src folder) for the program to find it.
When you create Scanner like this new Scanner(new File("input100K.txt").getAbsolutePath()); you are scanning file path as input not file itself. Do it this way new Scanner(new File("input100K.txt"));
You can try using split() method on the line you just have read, then parsing each part to a double. Note that it's not necessary to create two Scanners:
Scanner sc = new Scanner(new File("input100K.txt"));
sc.useDelimiter(" ");
ArrayList<Double> list = new ArrayList<Double>();
while (sc.hasNextLine()) {
String[] parts = sc.nextLine().split(" "); // split each line by " "
for (String s : parts) {
list.add(Double.parseDouble(s)); // parse to double
}
}
sc.close();
System.out.println(list);
replace the line
Scanner numFile = new Scanner(new File("input100K.txt").getAbsolutePath());
with
Scanner numFile = new Scanner(new File("input100K.txt"));
Here is a sample program :
public static void main(String[] args) throws FileNotFoundException {
List<Double> doubleList = new ArrayList<Double>();
Scanner scanner = new Scanner(new File("/home/visruthcv/inputfile.txt"));
while (scanner.hasNextDouble()) {
double value = scanner.nextDouble();
System.out.println(value);
doubleList.add(value);
}
/*
* for test print
*/
for (Double eachValue : doubleList) {
System.out.println(eachValue);
}
}
Related
I am solving a problem from Advent of Code, and trying to put the content of the input file into an arraylist, here's my code for that:
ArrayList<Integer> arrayList = new ArrayList<>();
try (Scanner s = new Scanner(new File("input.txt")).useDelimiter(",")) {
while (s.hasNext()) {
int b = Integer.parseInt(s.next());
arrayList.add(b);
}
}
catch (FileNotFoundException e) {
// Handle the potential exception
}
System.out.println(arrayList);
and when I run it, it does not print the arraylist. I can't understand why, could someone tell me what I did wrong?
I used StringTokenizer and it works perfectly. I am not familiar with using Scanner to split items, so I converted it over into a StringTokenizer. Hope you're okay with that.
public static void main(String[] args) throws IOException {
ArrayList<Integer> arrayList = new ArrayList<>();
Scanner s = new Scanner(new File("input.in"));
StringTokenizer st = new StringTokenizer(s.nextLine(), ",");
while (st.hasMoreTokens()) {
int b = Integer.parseInt(st.nextToken());
arrayList.add(b);
}
s.close();
System.out.println(arrayList);
}
This fills your ArrayList with the values you want
You can validate if you are able to read the file or not. Your code can be modifed something like this. Please check if it prints "File found". If not it means that file you are trying to read is not in classpath. You might want to refer https://mkyong.com/java/java-how-to-read-a-file/
...
File source = new File("input.txt");
if(source.exists()) {
System.out.println("File found");
}
try (Scanner s = new Scanner(source).useDelimiter(",")) {
...
Im trying to make a program that reads data from a text file which contains student names and scores they got on a test. I want to output it in this sort of way
Im starting off by trying to read the txt file so I can then re arrange them and then outputting it into another file but im not sure what im doing wrong. Instead it prints into the exe instead of the file I want it to print to.
import java.io.File;
import java.util.Scanner;
public class ReadConsole {
public static void main(String[] args) {
try {
Scanner input = new Scanner(System.in);
System.out.print("Enter the file name with extention : ");
File file = new File(input.nextLine());
input = new Scanner(file); //scans the file
while (input.hasNextLine()) {
String line = input.nextLine();
System.out.println(line);
}
input.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Click Here for Image
Instead of using System.out PrintStream, you can create a PrintStream that writes to a file:
PrintStream output = new PrintStream(new File("output.txt"));
while (input.hasNextLine()) {
String line = input.nextLine();
output.println(line);
}
Remember to close both input Scanner and output PrintStream:
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the file name with extention : ");
File file = new File(input.nextLine());
try (Scanner fileInput = new Scanner(file); // scans the file
PrintStream output = new PrintStream(new File("c:/output.txt"))) {
while (input.hasNextLine()) {
String line = input.nextLine();
output.println(line);
}
}
}
At the moment my code does nothing when i input a valid .txt file. I would like to print the number of lines the file contains. Could anyone tell me why nothing is currently happening?
public class Task3
{
public static void main(String[] args) throws FileNotFoundException
{
// instance variables
int characterCount = 0;
int wordCount = 0;
int lineCount = 0;
// create a Scanner object to read in file name from console input
Scanner in = new Scanner(System.in);
System.out.print("Please enter the file name: ");
String filename = in.next();
File inputFile = new File(filename);
// create a Scanner object to read the actual text file
Scanner inFile = new Scanner(inputFile);
int lines = 0;
while (inFile.hasNextLine())
{ // enter while loop if there is a complete line available
in.nextLine();
lines++;
// increase line counter variable
}
System.out.println(lines);
You're not reading lines from the file, you're reading them from standard input.
In this loop:
while (inFile.hasNextLine())
{ // enter while loop if there is a complete line available
in.nextLine();
lines++;
// increase line counter variable
}
You are using the Scanner for System.in, not the scanner you created for the file. So the call to nextLine will wait for your input instead of going to the next line in the file. That's why it seems that nothing is happening.
Replace in.nextLine with inFile.nextLine and it will work.
Change:
in.nextLine();
To:
inFile.nextLine();
Add a System.out.println(inputFile.exists()) to see that you are not creating a new file.
I'm trying to read in from two files and store them in two separate arraylists. The files consist of words which are either alone on a line or multiple words on a line separated by commas.
I read each file with the following code (not complete):
ArrayList<String> temp = new ArrayList<>();
FileInputStream fis;
fis = new FileInputStream(fileName);
Scanner scan = new Scanner(fis);
while (scan.hasNextLine()) {
Scanner input = new Scanner(scan.nextLine());
input.useDelimiter(",");
while (scan.hasNext()) {
String md5 = scan.next();
temp.add(md5);
}
}
scan.close();
return temp;
Each file contains almost 1 million words (I don't know the exact number), so I'm not entirely sure that the above code works correctly - but it seems to.
I now want to find out how many words are exclusive to the first file/arraylist. To do so I planned on using list1.removeAll(list2) and then checking the size of list1 - but for some reason this is not working. The code:
public static ArrayList differentWords(String fileName1, String fileName2) {
ArrayList<String> file1 = readFile(fileName1);
ArrayList<String> file2 = readFile(fileName2);
file1.removeAll(file2);
return file1;
}
My main method contains a few different calls and everything works fine until I reach the above code, which just causes the program to hang (in netbeans it's just "running").
Any idea why this is happening?
You are not using input in
while (scan.hasNextLine()) {
Scanner input = new Scanner(scan.nextLine());
input.useDelimiter(",");
while (scan.hasNext()) {
String md5 = scan.next();
temp.add(md5);
}
}
I think you meant to do this:
while (scan.hasNextLine()) {
Scanner input = new Scanner(scan.nextLine());
input.useDelimiter(",");
while (input.hasNext()) {
String md5 = input.next();
temp.add(md5);
}
}
but that said you should look into String#split() that will probably save you some time:
while (scan.hasNextLine()) {
String line = scan.nextLine();
String[] tokens = line.split(",");
for (String token: tokens) {
temp.add(token);
}
}
try this :
for(String s1 : file1){
for(String s2 : file2){
if(s1.equals(s2)){file1.remove(s1))}
}
}
I have a simple Java questions and I need a simple answer, if possible. I need to input the data from the file and store the data into an array. To do this, I will have to have the program open the data file, count the number of elements in the file, close the file, initialize your array, reopen the file and load the data into the array. I am mainly having trouble getting the file data stored as an array. Here's what I have:
The to read file is here: https://www.dropbox.com/s/0ylb3iloj9af7qz/scores.txt
import java.io.*;
import java.util.*;
import javax.swing.*;
import java.text.*;
public class StandardizedScore8
{
//Accounting for a potential exception and exception subclasses
public static void main(String[] args) throws IOException
{
// TODO a LOT
String filename;
int i=0;
Scanner scan = new Scanner(System.in);
System.out.println("\nEnter the file name:");
filename=scan.nextLine();
File file = new File(filename);
//File file = new File ("scores.txt");
Scanner inputFile = new Scanner (file);
String [] fileArray = new String [filename];
//Scanner inFile = new Scanner (new File ("scores.txt"));
//User-input
// System.out.println("Reading from 'scores.txt'");
// System.out.println("\nEnter the file name:");
// filename=scan.nextLine();
//File-naming/retrieving
// File file = new File(filename);
// Scanner inputFile = new Scanner(file);
I recommend you use a Collection. This way, you don't have to know the size of the file beforehand and you'll read it only once, not twice. The Collection will manage its own size.
Yes, you can if you don't care about the trouble of doing things twice. Use while(inputFile.hasNext()) i++;
to count the number of elements and create an array:
String[] scores = new String[i];
If you do care, use a list instead of an array:
List<String> list = new ArrayList<String>();
while(inputFile.hasNext()) list.add(inputFile.next());
You can get list elements like list.get(i), set list element like list.set(i,"string") and get the length of list list.size().
By the way, your line of String [] fileArray = new String [filename];is incorrect. You need to use an int to create an array instead of a String.
/*
* Do it the easy way using a List
*
*/
public static void main(String[] args) throws IOException
{
Scanner scan = new Scanner(System.in);
System.out.println("\nEnter the file name:");
String filename = scan.nextLine();
FileReader fileReader = new FileReader(filename);
BufferedReader reader = new BufferedReader(fileReader);
List<String> lineList = new ArrayList<String>();
String thisLine = reader.readLine();
while (thisLine != null) {
lineList.add(thisLine);
thisLine = reader.readLine();
}
// test it
int i = 0;
for (String testLine : lineList) {
System.out.println("Line " + i + ": " + testLine);
i++;
}
}
We can use the ArrayList collection to store the values from the file to the array without knowing the size of the array before hand.
You can get more info on ArrayList collections from the following urls.
http://docs.oracle.com/javase/tutorial/collections/implementations/index.html
http://www.java-samples.com/showtutorial.php?tutorialid=234