Reading from a textfile in Java - java

I am trying to read the following from a textfile
12
650 64 1
16 1024 2
How do I put this in a list or give them variables?
Tried this
class Test{
Scanner lese = new Scanner(new File("regneklynge.txt"));`
ArrayList<String> list = new ArrayList<String>();`
while (lese.hasNext()){`
list.add(lese.next());`
}
}

Check this article our for reading from a file.
Then, you can use Java's Scanner class to read individual items and put them into a list.
For example:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.ArrayList;
public class ReadFromFile {
public static void main(String[] args) {
File file = new File("file-name.txt");
try {
Scanner scanner = new Scanner(file);
List<Integer> myIntList = new ArrayList<>();
while (scanner.hasNext()) {
int i = scanner.nextInt();
myIntList.add(i);
}
scanner.close();
// now you have an ArrayList with the numbers in it that you can use
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}

Related

How to add doubles from a string to an arraylist of doubles?

I have to add a student for each line in the students.txt file and also add the grades from it to the new student. The student object has 4 properties, name (string), last name(string), number(int), and grades (arraylist double)
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class readFile {
public static void main(String[] args) {
ArrayList<student> students = new ArrayList<>();
int linecnt = 0;
try(BufferedReader br = new BufferedReader(new FileReader("students.txt"))) {
String line;
while((line = br.readLine()) != null) {
students.add(new student("", "", 0));
Scanner scan = new Scanner(line);
if(scan.hasNextDouble()) {
students.get(linecnt).addGrade(scan.nextDouble());
}
linecnt++;
}
} catch(FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
When I run this nothing happens, no errors, just a blank white space. What is the problem?
You Have not said what should be the output.
The answer to your question is
How to add doubles from a string to an arraylist of doubles?
String text = "12.34";
double value = Double.parseDouble(text);
arraylist.add(value);

Java issue with reading a text file into an ArrayList

I have created a program that is supposed to read a text file for Integers and put them into an Arraylist, and then there are a bunch of methods to act on it. but, after some trouble shooting I am noticing that my program won't pull the integers from the text file in. Could anyone point me in the right direction?
package project1;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;
import java.lang.System;
public class Main {
public static void main(String[] Args) {
Main mainObject = new Main();
mainObject.run();
}
public void run() {
**ArrayList<Integer> list = new ArrayList<>();
String fileName = "p01-in.txt";
Scanner in = new Scanner(fileName);
while (in.hasNextInt()) {
list.add(in.nextInt());
int line = in.nextInt();
System.out.println("%s %n" + line);
}
in.close();**
ArrayList<Integer> listRunsUpCount = new ArrayList<>();
ArrayList<Integer> listRunsDnCount = new ArrayList<>();
Main findRuns = new Main();
listRunsUpCount = findRuns.FindRuns(list, 0);
listRunsDnCount = findRuns.FindRuns(list, 1);
ArrayList<Integer> listRunsCount = new ArrayList<>();
Main mergeRuns = new Main();
listRunsCount = mergeRuns.MergeRuns(listRunsUpCount,
listRunsDnCount);
Main Output = new Main();
Output.Output("p01-runs.txt", listRunsCount);
}
You can use BufferedReader to read file content line by line.
try {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String line=reader.readLine();
while (line != null) {
line = reader.readLine();
list.add(Integer.parseInt(line.trim()));
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}

using Java arraylist for storing data from scan from file

I am new to java, but not coding. I am trying to figure out java because it's part of my class this term and I am having a really hard problem grasping the idea of it and implementing things in java.
my problem Is that I am not sure if I am correctly using the arraylist to grab data from the scan of the file and input it into a arraylist to sort and print at a later time. I am just having issues picking up on java any help would be great since I am new to java.
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.regex.Pattern;
import java.util.ArrayList;
import java.util.*;
public class MissionCount
{
private static ArrayList<String> list = new ArrayList<String>();
// returns an InputStream that gets data from the named file
private static InputStream getFileInputStream(String fileName) throws Exception {
InputStream inputStream;
try {
inputStream = new FileInputStream(new File(fileName));
}
catch (FileNotFoundException e) { // no file with this name exists
inputStream = null;
throw new Exception("unable to open the file -- " + e.getMessage());
}
return inputStream;
}
public static void main(String[] args) {
if (args.length != 1) {
System.out.println("USage: MissionCount <datafile>");
//System.exit(1);
}
try {
System.out.printf("CS261 - MissionCount - Chad Dreher%n%n");
int crewcount = 0;
int misscount = 0;
InputStream log = getFileInputStream(args[0]);
Scanner sc = new Scanner(log);
sc.useDelimiter(Pattern.compile(",|\n"));
while (sc.hasNext()) {
String crewMember = sc.next();
list.add(crewMember);
String mission = sc.next();
list.add(mission);
}
sc.close();
// Add code to print the report here
}catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
InputStream log = getFileInputStream(args[0]);
Change that line to as follows :-
File log = new File(args[0])
that should work!

Once it has taken input(words) from a file, how to terminate at a specific word?

How would I go about making my program terminate once it reaches a specific word from a file. So far, I have it printing out all the words from the file which I want. "input" contains the words "one two three four galumph" just like that.
import java.util.Scanner;
import java.io.*;
class EchoWords {
public static void main(String[] args) throws FileNotFoundException {
Scanner sc2 = null;
try {
sc2 = new Scanner(new File("input"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
while (sc2.hasNextLine()) {
Scanner s2 = new Scanner(sc2.nextLine());
while (sc2.hasNext()) {
String s = s2.next();
System.out.println(s);
}
}
}
}

Take numbers from a file and sort them

I need to make my program read a file, then take the numbers in the string and sort them into an array. I can get my program to read the file and put it to a string, but that's where I'm stuck. All the numbers are on different lines in the file, but appear as one long number in the string. This is what I have so far:
public static void main(String[] args) {
String ipt1;
Scanner fileInput;
File inFile = new File("input1.dat");
try {
fileInput = new Scanner(inFile);
//Reads file contents
while (fileInput.hasNext()) {
ipt1 = fileInput.next();
System.out.print(ipt1);
}
fileInput.close();
}
catch (FileNotFoundException e) {
System.out.println(e);
}
}
I recommend reading the values in as numeric types using fileInput.nextInt() or whatever type you want them, putting them in an array and using a built in sort like Arrays.sort. Unless I'm missing a more subtle point about the question.
If your task is just to get input from some file and you're sure the file has integers, use an ArrayList.
import java.util.*;
Scanner fileInput;
ArrayList<Double>ipt1 = new ArrayList<Double>();
File inFile = new File("input1.dat");
try {
fileInput = new Scanner(inFile);
//Reads file contents
while (fileInput.hasNext()){
ipt1.add(fileInput.nextDouble()); //Adds the next Double to the ArrayList
System.out.print(ipt1.get(ipt1.size()-1)); //Prints out what you just got.
}
fileInput.close();
}
catch (FileNotFoundException e){
System.out.println(e);
}
//Sorting time
//This uses the built-in Array sorting.
Collections.sort(ipt1);
However, if you DO need to come up with a simple array in the end, but CAN use ArrayLists, you can add the following:
Double actualResult[] = new Double[ipt1.size()]; //Declare array
for(int i = 0; i < ipt1.size(); ++i){
actualResult[i] = ipt1.get(i);
}
Arrays.sort(actualResult[]);
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
public class SortNumberFromFile {
public static void main(String[] args) throws IOException {
BufferedReader br = null;
try {
System.out.println("Started at " + LocalDateTime.now());
br = new BufferedReader(new FileReader("/folder/fileName.csv"));//Read data from file named /folder/fileName.csv
List<Long> collect = br.lines().mapToLong(a -> Long.parseLong(a)).boxed().collect(Collectors.toList());//Collect all read data in list object
Collections.sort(collect);//Sort the data
writeRecordsToFile(collect, "/folder/fileName.txt");//Write sorted data to file named /folder/fileName.txt
System.out.println("Ended at " + LocalDateTime.now());
}
finally {
br.close();
}
}
public static <T> void writeRecordsToFile(Collection<? extends T> items, String filePath) {
BufferedWriter writer = null;
File file = new File(filePath);
try {
if(!file.exists()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
writer = new BufferedWriter(new FileWriter(filePath, true));
if(items != null && items.size() > 0) {
for(T eachItem : items) {
if(eachItem != null) {
writer.write(eachItem.toString());
writer.newLine();
}
}
}
} catch (IOException ex) {
}finally {
try {
writer.close();
} catch (IOException e) {
}
}
}
}

Categories

Resources