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();
}
Related
The code should do a reverse and output the result to out.txt, but this does not happen, can you explain my mistake in the code. Thanks in advance
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
FileReader input = new FileReader("in.txt");
FileWriter output = new FileWriter("out.txt");
BufferedReader sb = new BufferedReader(input);
String data;
while ((data = sb.readLine()) != null) {
String[] words = data.split(" ");
for (String a : words) {
StringBuilder builder = new StringBuilder(a);
builder.reverse();
while ((sb.read()) != -1) {
output.write(String.valueOf(builder.reverse()));
}
}
}
}
}
You are trying to reverse the string twice because of that the string is getting back to the original string. Also, there is an unnecessary (as per my understanding) while loop inside the for loop (I have removed that in my answer).
Try the below code:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
FileReader input = new FileReader("in.txt");
FileWriter output = new FileWriter("out.txt");
BufferedReader sb = new BufferedReader(input);
String data;
while ((data = sb.readLine()) != null) {
String[] words = data.split(" ");
// above statement can be replaced with
// String[] words = data.split(" {34}");
for (String a : words) {
StringBuilder builder = new StringBuilder(a);
// why while loop is required?
//while ((sb.read()) != -1) {
output.write(builder.reverse().toString());
output.flush(); // flush data to the file
//}
}
}
output.close();
}
}
Read about File writer here on how to flush data and also close the writer after writing is completed.
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);
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();
}
}
}
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) {
}
}
}
}
I am trying to read contents of a file using string tokenizer and store all the tokens in an array but i keep getting exception in main error. I need advise on how to do this.Below is the code am using for that;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.StringTokenizer;
public class FileTokenizer
{
private static final String DEFAULT_DELIMITERS = "< , { } >";
private static final String DEFAULT_TEST_FILE = "trans1.txt";
public List<String> tokenize(Reader reader) throws IOException
{
List<String> tokens = new ArrayList<String>();
BufferedReader br = null;
try
{
int i = 0;
br = new BufferedReader(reader);
Scanner scanner = new Scanner(br);
while (scanner.hasNext())
{
StringTokenizer st = new StringTokenizer(scanner.next(), DEFAULT_DELIMITERS, true);
while (st.hasMoreElements())
{
String[] t = new String[200];
tokens.add(st.nextToken());
t[i] = st.nextToken();
System.out.println(t[i]);
i++;
}
}
}
finally
{
close(br);
}
return tokens;
}
public static void close(Reader r)
{
try
{
if (r != null)
{
r.close();
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
try
{
String fileName = ((args.length > 0) ? args[0] : DEFAULT_TEST_FILE);
FileReader fileReader = new FileReader(new File(fileName));
FileTokenizer fileTokenizer = new FileTokenizer();
List<String> tokens = fileTokenizer.tokenize(fileReader);
//System.out.println(tokens);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
My file looks like;
PDA = (
{ q1, q2, q3, q4},
{ 0, 1 },
{ 0, $ },
{ (q1, #, #) -> { (q2, $) }, (q2, 0, #) -> { (q2, 0) },
(q2, 1, 0) -> { (q3, #) }, (q3, 1, 0) -> { (q3, #) },
(q3, #, $) -> { (q4, #) } },
q1,
{ q1, q4}
)
You will get the java.util.NoSuchElementException since you are calling st.nextToken() twice within the loop
while (st.hasMoreElements())
Modifying harigm's example, you can then add t[i] to tokens as you require
String[] t = new String[200];
System.out.println(t[i]);
tokens.add(t[i]);
Delimiters shouldn't be separated by spaces:
private static final String DEFAULT_DELIMITERS = "<,{}>";
Also, keep the following in mind (from the Javadoc):
StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead.
String.split() was introduced in JDK 1.4.
That said:
Using a Scanner to tokenize a stream together with a StringTokenizer looks a bit weird to me;
You call st.nextToken() twice in the inner loop;
t is useless. You re-create it each time in your inner loop and use only one element of it.
It seems that what you are trying to build is a lexical analyzer. Maybe you should look up some documentation on the subject.
HI,
I have modified your code and Now works perfectly fine, check this
package org.sample;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.StringTokenizer;
public class FileTokenizer
{
private static final String DEFAULT_DELIMITERS = "< , { } >";
// private static final String DEFAULT_TEST_FILE = "trans1.txt";
public List<String> tokenize(Reader reader) throws IOException
{
List<String> tokens = new ArrayList<String>();
BufferedReader br = null;
try
{
int i = 0;
br = new BufferedReader(reader);
Scanner scanner = new Scanner(br);
while (scanner.hasNext())
{
StringTokenizer st = new StringTokenizer(scanner.next(), DEFAULT_DELIMITERS, true);
while (st.hasMoreElements())
{
String[] t = new String[200];
// tokens.add(st.nextToken());
// t[i] = st.nextToken();
System.out.println(t[i]);
i++;
}
}
}
finally
{
close(br);
}
return tokens;
}
public static void close(Reader r)
{
try
{
if (r != null)
{
r.close();
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
public static void main(String[] args)
{
try
{
// String fileName = ((args.length > 0) ? args[0] : DEFAULT_TEST_FILE);
FileReader fileReader = new FileReader(new File("c:\\DevTest\\1.txt"));
FileTokenizer fileTokenizer = new FileTokenizer();
List<String> tokens = fileTokenizer.tokenize(fileReader);
//System.out.println(tokens);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
Looking at your input file, I should point out that its hierarchical and irregular structure makes it more suited to be parsed by an actual parser. You may have to learn how to use a parser generator and write a lexer and grammar for it etc, but in the end you'll end up with a much more maintainable code. Doing this yourself is rather painstaking and error-prone.
I recommend ANTLR. It's quite mature, and it has a wide enough user base that I'm sure you can get help easily.