Java reading a file into an ArrayList? - java

How do you read the contents of a file into an ArrayList<String> in Java?
Here are the file contents:
cat
house
dog
.
.
.

This Java code reads in each word and puts it into the ArrayList:
Scanner s = new Scanner(new File("filepath"));
ArrayList<String> list = new ArrayList<String>();
while (s.hasNext()){
list.add(s.next());
}
s.close();
Use s.hasNextLine() and s.nextLine() if you want to read in line by line instead of word by word.

You can use:
List<String> list = Files.readAllLines(new File("input.txt").toPath(), Charset.defaultCharset() );
Source: Java API 7.0

A one-liner with commons-io:
List<String> lines = FileUtils.readLines(new File("/path/to/file.txt"), "utf-8");
The same with guava:
List<String> lines =
Files.readLines(new File("/path/to/file.txt"), Charset.forName("utf-8"));

Simplest form I ever found is...
List<String> lines = Files.readAllLines(Paths.get("/path/to/file.txt"));

In Java 8 you could use streams and Files.lines:
List<String> list = null;
try (Stream<String> lines = Files.lines(myPathToTheFile))) {
list = lines.collect(Collectors.toList());
} catch (IOException e) {
LOGGER.error("Failed to load file.", e);
}
Or as a function including loading the file from the file system:
private List<String> loadFile() {
List<String> list = null;
URI uri = null;
try {
uri = ClassLoader.getSystemResource("example.txt").toURI();
} catch (URISyntaxException e) {
LOGGER.error("Failed to load file.", e);
}
try (Stream<String> lines = Files.lines(Paths.get(uri))) {
list = lines.collect(Collectors.toList());
} catch (IOException e) {
LOGGER.error("Failed to load file.", e);
}
return list;
}

List<String> words = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new FileReader("words.txt"));
String line;
while ((line = reader.readLine()) != null) {
words.add(line);
}
reader.close();

You can for example do this in this way (full code with exceptions handlig):
BufferedReader in = null;
List<String> myList = new ArrayList<String>();
try {
in = new BufferedReader(new FileReader("myfile.txt"));
String str;
while ((str = in.readLine()) != null) {
myList.add(str);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null) {
in.close();
}
}

//CS124 HW6 Wikipedia Relation Extraction
//Alan Joyce (ajoyce)
public List<String> addWives(String fileName) {
List<String> wives = new ArrayList<String>();
try {
BufferedReader input = new BufferedReader(new FileReader(fileName));
// for each line
for(String line = input.readLine(); line != null; line = input.readLine()) {
wives.add(line);
}
input.close();
} catch(IOException e) {
e.printStackTrace();
System.exit(1);
return null;
}
return wives;
}

Here's a solution that has worked pretty well for me:
List<String> lines = Arrays.asList(
new Scanner(new File(file)).useDelimiter("\\Z").next().split("\\r?\\n")
);
If you don't want empty lines, you can also do:
List<String> lines = Arrays.asList(
new Scanner(new File(file)).useDelimiter("\\Z").next().split("[\\r\\n]+")
);

To share some analysis info. With a simple test how long it takes to read ~1180 lines of values.
If you need to read the data very fast, use the good old BufferedReader FileReader example. It took me ~8ms
The Scanner is much slower. Took me ~138ms
The nice Java 8 Files.lines(...) is the slowest version. Took me ~388ms.

Here is an entire program example:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class X {
public static void main(String[] args) {
File f = new File("D:/projects/eric/eclipseworkspace/testing2/usernames.txt");
try{
ArrayList<String> lines = get_arraylist_from_file(f);
for(int x = 0; x < lines.size(); x++){
System.out.println(lines.get(x));
}
}
catch(Exception e){
e.printStackTrace();
}
System.out.println("done");
}
public static ArrayList<String> get_arraylist_from_file(File f)
throws FileNotFoundException {
Scanner s;
ArrayList<String> list = new ArrayList<String>();
s = new Scanner(f);
while (s.hasNext()) {
list.add(s.next());
}
s.close();
return list;
}
}

Scanner scr = new Scanner(new File(filePathInString));
/*Above line for scanning data from file*/
enter code here
ArrayList<DataType> list = new ArrayList<DateType>();
/*this is a object of arraylist which in data will store after scan*/
while (scr.hasNext()){
list.add(scr.next());
}
/*above code is responsible for adding data in arraylist with the help of add function */

Add this code to sort the data in text file.
Collections.sort(list);

Related

Replace the first line with the longest java text file

i need to replace the first line in the text file with the longest and vice versa. Please tell me what i need to fix and add. At this stage the program looks for the longest line properly. I'm new to Java, I'm sure there is not much to fix, but I do not know what exactly is needed. Also, if possible, help implement the output of the result in a new file.
The code still looks like this:
package pkg;
import java.io.*;
import java.nio.file.Files;
import java.util.*;
public class Main {
static int previousLongLine = 0;
public void printLongLine(HashMap longLineMap) {
Set keyofSet = longLineMap.keySet();
Iterator itr = keyofSet.iterator();
while (itr.hasNext()) {
Integer keys = (Integer) itr.next();
String value = (String) longLineMap.get(keys);
System.out.println("Line Number of Longest line: " + keys
+ "\nLongest line: " + value);
}
}
public static void main(String []args){
// TODO Auto-generated method stub
String fileName = "G:\\colege\\bursa\\Colege\\Programing\\pkg\\File1.txt";
// This will reference one line at a time
String line = null;
int key = 0;
int lineSize = 0, lineNumber = 0;
Main ln = new Main();
HashMap longLineMap = new HashMap();
try {
// FileReader reads text files in the default encoding.
FileReader fileReader = new FileReader(fileName);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader = new BufferedReader(fileReader);
while ((line = bufferedReader.readLine()) != null) {
lineNumber++;
lineSize = line.length();
if (lineSize > previousLongLine) {
previousLongLine = lineSize;
longLineMap.clear();
longLineMap.put(lineNumber, line);
}
if(lineNumber == 1){
String old = line;
String newl = old.replaceFirst(old, String.valueOf(previousLongLine));
}
}
//close files.
bufferedReader.close();
} catch (FileNotFoundException ex) {
System.out.println("Unable to open file '" + fileName + "'");
} catch (IOException ex) {
System.out.println("Error reading file '" + fileName + "'");
}
ln.printLongLine(longLineMap);
}
}
You can achieve this with a simple stream operation.
Info on stream: https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html
I've used try-with-resource, which auto-closes the resource after processing has ceased.
Info on try-with-resource: https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
Read file into an ArrayList
Create another List to hold the sorted elements.
Open a stream on the ArrayList which holds the input data.
Sort the lines into size order. Use Comparator.reverseOrder() for largest to smallest
Using a downstream collector store the output as a new list.
Write sorted list to file.
Reading file:
String inputFile = "files/longestLine.txt";
List<String> lines = new ArrayList<>();
try(BufferedReader bufferedReader = new BufferedReader(new FileReader(inputFile))) {
String line = bufferedReader.readLine();
while(line != null){
lines.add(line);
line = bufferedReader.readLine();
}
} catch (IOException e) {
e.printStackTrace();
}
Use a stream to sort the lines into size order.
List<String> sortedLines = lines.stream()
.sorted(Comparator.reverseOrder())
.collect(Collectors.toList());
Write to file:
String outputFile = "outputFile.txt";
try(BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(outputFile))) {
for (String line: sortedLines) {
bufferedWriter.write(line);
bufferedWriter.newLine();
}
} catch (IOException e) {
e.printStackTrace();
}

When importing a txt file, is there a way to specify how you want it formatted? [duplicate]

How can I open a .txt file and read numbers separated by enters or spaces into an array list?
Read file, parse each line into an integer and store into a list:
List<Integer> list = new ArrayList<Integer>();
File file = new File("file.txt");
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String text = null;
while ((text = reader.readLine()) != null) {
list.add(Integer.parseInt(text));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
}
}
//print out the list
System.out.println(list);
A much shorter alternative is below:
Path filePath = Paths.get("file.txt");
Scanner scanner = new Scanner(filePath);
List<Integer> integers = new ArrayList<>();
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
integers.add(scanner.nextInt());
} else {
scanner.next();
}
}
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. Although default delimiter is whitespace, it successfully found all integers separated by new line character.
Good news in Java 8 we can do it in one line:
List<Integer> ints = Files.lines(Paths.get(fileName))
.map(Integer::parseInt)
.collect(Collectors.toList());
try{
BufferedReader br = new BufferedReader(new FileReader("textfile.txt"));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}finally{
in.close();
}
This will read line by line,
If your no. are saperated by newline char. then in place of
System.out.println (strLine);
You can have
try{
int i = Integer.parseInt(strLine);
}catch(NumberFormatException npe){
//do something
}
If it is separated by spaces then
try{
String noInStringArr[] = strLine.split(" ");
//then you can parse it to Int as above
}catch(NumberFormatException npe){
//do something
}
File file = new File("file.txt");
Scanner scanner = new Scanner(file);
List<Integer> integers = new ArrayList<>();
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
integers.add(scanner.nextInt());
}
else {
scanner.next();
}
}
System.out.println(integers);
import java.io.*;
public class DataStreamExample {
public static void main(String args[]){
try{
FileWriter fin=new FileWriter("testout.txt");
BufferedWriter d = new BufferedWriter(fin);
int a[] = new int[3];
a[0]=1;
a[1]=22;
a[2]=3;
String s="";
for(int i=0;i<3;i++)
{
s=Integer.toString(a[i]);
d.write(s);
d.newLine();
}
System.out.println("Success");
d.close();
fin.close();
FileReader in=new FileReader("testout.txt");
BufferedReader br=new BufferedReader(in);
String i="";
int sum=0;
while ((i=br.readLine())!= null)
{
sum += Integer.parseInt(i);
}
System.out.println(sum);
}catch(Exception e){System.out.println(e);}
}
}
OUTPUT::
Success
26
Also, I used array to make it simple.... you can directly take integer input and convert it into string and send it to file.
input-convert-Write-Process... its that simple.

How to read | separated csv file in java? [duplicate]

This question already has answers here:
Calculating Average from a CSV File
(4 answers)
Closed 7 years ago.
I have pie | separated csv file. I want to read this file in java. I have a java code which read comma separated file in java but it fails at | separated csv file
My file contains "CUSTOMER CODE | PRODUCT CODE | SEND TO BANK | SEND TO BRANCH"
This type of data not comma separated.
Java code
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
public class TestPieCSVtoXLs {
public static void main(String[] args) {
String csvFile = "D:\\VijayTest\\csvFile.csv";
DataInputStream myInput;
String thisLine;
ArrayList<ArrayList<String>> arList = new ArrayList<ArrayList<String>>();
ArrayList<String> al = new ArrayList<String>();
BufferedReader br = null;
try {
FileInputStream fis = new FileInputStream(csvFile);
myInput = new DataInputStream(fis);
while ((thisLine = myInput.readLine()) != null) {
al = new ArrayList<String>();
String strar[] = thisLine.split(",");
for (int j = 0; j < strar.length; j++) {
System.out.println(strar[j]);
al.add(strar[j]);
}
}
arList.add(al);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("Done");
}
}
you should change
String strar[] = thisLine.split(",");
to
String strar[] = thisLine.split("\\|");
Since | is a metacharacter in regex, you need to escape it.
Also as stated in the comments, this solutions doesn't take in account special cases...
OpenCSV is good library that can make your life easy while interacting with CSV in java.
code for reading | separated csv file in java
public static void main(String[] args) {
String csvFile = "D:\\VijayTest\\csvfile.csv";
DataInputStream myInput;
String thisLine;
ArrayList<ArrayList<String>> arList = new ArrayList<ArrayList<String>>();
ArrayList<String> al = new ArrayList<String>();
BufferedReader br = null;
try {
FileInputStream fis = new FileInputStream(csvFile);
myInput = new DataInputStream(fis);
while ((thisLine = myInput.readLine()) != null) {
al = new ArrayList<String>();
String strar[] = thisLine.split("\\|");
for (int j = 0; j < strar.length; j++) {
System.out.println(strar[j]);
al.add(strar[j]);
}
}
arList.add(al);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("Done");
}
Use uniVocity-parsers and be done with it:
CsvParserSettings settings = new CsvParserSettings();
settings.setLineSeparatorDetectionEnabled(true);
settings.getFormat().setDelimiter('|');
CsvParser parser = new CsvParser(settings);
List<String[]> allLines = parser.parseAll(YOUR_INPUT_HERE);
Its CSV parser can handle all sorts of inputs and is also the fastest CSV parser for Java.
Disclosure: I am the author of this library. It's open-source and free (Apache V2.0 license).

Reading into a string from a file, but any text after space on a line removed?

I have a large text file with phrases such as:
citybred JJ
Brestowe NNP
STARS NNP NNS
negative JJ NN
investors NNS NNPS
mountain NN
My objective is to keep the first word of each line, without the spaces, and also make them lowercase.
EX:
citybred
brestowe
stars
negative
investors
mountain
Would be returned if the above text was evaluated.
Any help?
Current code:
public class FileLinkList
{
public static void main(String args[])throws IOException{
String content = new String();
File file = new File("abc.txt");
LinkedList<String> list = new LinkedList<String>();
try {
Scanner sc = new Scanner(new FileInputStream(file));
while (sc.hasNextLine()){
content = sc.nextLine();
list.add(content);
}
sc.close();
} catch(FileNotFoundException fnf){
fnf.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
System.out.println("\nProgram terminated Safely...");
}
Collections.reverse(list);
Iterator i = list.iterator();
while (i.hasNext()) {
System.out.print("Node " + (count++) + " : ");
System.out.println(i.next());
}
}
}
If your token and its POS tag is separated by space :
public class FileLinkList{
public static void main(String[] args) {
BufferedReader br = null;
LinkedList<String> list = new LinkedList<String>();
String word;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("LEXICON.txt"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
word = sCurrentLine.trim().split(" ")[0];
list.add(word.toLowerCase());
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
Add the following:
content = sc.nextLine();
string[] tokens = content.split(new char[] {' '}, StringSplitOptions.RemovEemptyEntries);
// You can add some validations here...
string word = tokens[0].ToLowerCase();
Try this :
public class FileLinkList {
public static void main(String args[])throws IOException{
String content = new String();
int count=1;
File file = new File("abc.txt");
LinkedList<String> list = new LinkedList<String>();
try {
Scanner sc = new Scanner(new FileInputStream(file));
while (sc.hasNextLine()){
content = sc.nextLine();
if (content != null && content.length() > 0)) {
list.add(content.trim().split(" ")[0].toLowerCase());
}
}
sc.close();
} catch(FileNotFoundException fnf){
fnf.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
System.out.println("\nProgram terminated Safely...");
}
for (String listItem : list) {
System.out.println(listItem);
}
}
}
With Apache Commons IO it is much simpler to read a file into a list of Strings.
import org.apache.commons.io.FileUtils;
List<String> lines = FileUtils.readLines(new File("abc.txt"));
List<String firstWords = new ArrayList<>();
for (String line : lines) {
String firstWord = line.split(" ")[0].toLowerCase();
firstWords.add(firstWord);
}

converting lines of imported text file to arrays and printing arrays to make graph in Netbeans and Swing

I want to import any .txt files (note the .txt files will have a 3 sets of numbers in one column; separating each set with a space)
2
3
4
3
2
1
1
2
3
and convert the set of numbers into arrays. (array 1 , 2 and 3)
array1[] = {2,3,4}
array2[] = {3,2,1}
array3[] = {1,2,3}
then be able to graph the array in JFreeGraph Library
here's how i started...i'm using netbeans and java Swing
#Action
public void openMenuItem() {
int returnVal = jFileChooser1.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = jFileChooser1.getSelectedFile();
try {
FileReader fileReader = new FileReader(file);
jTextArea2.read(new FileReader(file.getAbsolutePath()), null);
} catch (IOException ex) {
System.out.println("problem accessing file" + file.getAbsolutePath());
}
} else {
System.out.println("File access cancelled by user.");
}
}
Read from a file line by line, perhaps using BufferedReader and readLine. Once you encounter an empty line - you have a new set of numbers. Here is an oversimplified example that maintains a list of lists, and reads only strings:
public static List<List<String>> parseFile(String fileName){
BufferedReader bufferedReader = null;
List<List<String>> lists = new ArrayList<List<String>>();
List<String> currentList = new ArrayList<String>();
lists.add(currentList);
try {
bufferedReader = new BufferedReader(new FileReader(fileName));
String line = null;
while ((line = bufferedReader.readLine()) != null) {
if (line.isEmpty()){
currentList = new ArrayList<String>();
lists.add(currentList);
} else {
currentList.add(line);
}
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
if (bufferedReader != null)
bufferedReader.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
return lists;
}
EDIT: using resulting lists with JTextArea
List<List<String>> lists = parseFile("test.txt");
for (List<String> strings : lists){
textArea.append(StringUtils.join(strings, ",") + "\n");
System.out.println(StringUtils.join(strings, ","));
}

Categories

Resources