Use a java.util.Scanner and java.util.List.
Scanner sc = new Scanner(new File(filename));
List<String> lines = new ArrayList<String>();
while (sc.hasNextLine()) {
lines.add(sc.nextLine());
}
String[] arr = lines.toArray(new String[0]);
Answer from polygenelubricants on Stack OverflowUse a java.util.Scanner and java.util.List.
Scanner sc = new Scanner(new File(filename));
List<String> lines = new ArrayList<String>();
while (sc.hasNextLine()) {
lines.add(sc.nextLine());
}
String[] arr = lines.toArray(new String[0]);
FileUtils.readLines(new File("/path/filename"));
From apache commons-io
This will get you a List of String. You can use List.toArray() to convert, but I'd suggest staying with List.
If you use Java 7 it can be done in two lines thanks to the Files#readAllLines method:
List<String> lines = Files.readAllLines(yourFile, charset);
String[] arr = lines.toArray(new String[lines.size()]);
Use a BufferedReader to read the file, read each line using readLine as strings, and put them in an ArrayList on which you call toArray at end of loop.
Java: Reading a file into an array - Stack Overflow
Java read file and store text in an array - Stack Overflow
How to read from text file and store in String array in Java? - Stack Overflow
java - reading from text file to string array - Stack Overflow
Use an ArrayList or an other dynamic datastructure:
BufferedReader abc = new BufferedReader(new FileReader(myfile));
List<String> lines = new ArrayList<String>();
while((String line = abc.readLine()) != null) {
lines.add(line);
System.out.println(data);
}
abc.close();
// If you want to convert to a String[]
String[] data = lines.toArray(new String[]{});
File txt = new File("file.txt");
Scanner scan = new Scanner(txt);
ArrayList<String> data = new ArrayList<String>() ;
while(scan.hasNextLine()){
data.add(scan.nextLine());
}
System.out.println(data);
String[] simpleArray = data.toArray(new String[]{});
Here is some example code to help you get started:
package com.acme;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class FileArrayProvider {
public String[] readLines(String filename) throws IOException {
FileReader fileReader = new FileReader(filename);
BufferedReader bufferedReader = new BufferedReader(fileReader);
List<String> lines = new ArrayList<String>();
String line = null;
while ((line = bufferedReader.readLine()) != null) {
lines.add(line);
}
bufferedReader.close();
return lines.toArray(new String[lines.size()]);
}
}
And an example unit test:
package com.acme;
import java.io.IOException;
import org.junit.Test;
public class FileArrayProviderTest {
@Test
public void testFileArrayProvider() throws IOException {
FileArrayProvider fap = new FileArrayProvider();
String[] lines = fap
.readLines("src/main/java/com/acme/FileArrayProvider.java");
for (String line : lines) {
System.out.println(line);
}
}
}
Hope this helps.
import java.io.File;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
// ...
Path filePath = new File("fileName").toPath();
Charset charset = Charset.defaultCharset();
List<String> stringList = Files.readAllLines(filePath, charset);
String[] stringArray = stringList.toArray(new String[]{});
Stored as strings:
public class ReadTemps {
public static void main(String[] args) throws IOException {
// TODO code application logic here
// // read KeyWestTemp.txt
// create token1
String token1 = "";
// for-each loop for calculating heat index of May - October
// create Scanner inFile1
Scanner inFile1 = new Scanner(new File("KeyWestTemp.txt")).useDelimiter(",\\s*");
// Original answer used LinkedList, but probably preferable to use ArrayList in most cases
// List<String> temps = new LinkedList<String>();
List<String> temps = new ArrayList<String>();
// while loop
while (inFile1.hasNext()) {
// find next line
token1 = inFile1.next();
temps.add(token1);
}
inFile1.close();
String[] tempsArray = temps.toArray(new String[0]);
for (String s : tempsArray) {
System.out.println(s);
}
}
}
For floats:
import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
public class ReadTemps {
public static void main(String[] args) throws IOException {
// TODO code application logic here
// // read KeyWestTemp.txt
// create token1
// for-each loop for calculating heat index of May - October
// create Scanner inFile1
Scanner inFile1 = new Scanner(new File("KeyWestTemp.txt")).useDelimiter(",\\s*");
// Original answer used LinkedList, but probably preferable to use ArrayList in most cases
// List<Float> temps = new LinkedList<Float>();
List<Float> temps = new ArrayList<Float>();
// while loop
while (inFile1.hasNext()) {
// find next line
float token1 = inFile1.nextFloat();
temps.add(token1);
}
inFile1.close();
Float[] tempsArray = temps.toArray(new Float[0]);
for (Float s : tempsArray) {
System.out.println(s);
}
}
}
If you don't know the number of lines in your file, you don't have a size with which to init an array. In this case, it makes more sense to use a List :
List<String> tokens = new ArrayList<String>();
while (inFile1.hasNext()) {
tokens.add(inFile1.nextLine());
}
After that, if you need to, you can copy to an array :
String[] tokenArray = tokens.toArray(new String[0]);
Try something like this :-
FileInputStream in = new FileInputStream("file.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
String[] filearray;
filearray = new String[10];
while ((strLine = br.readLine()) != null) {
for (int j = 0; j < myarray.length; j++){
filearray[j] = br.readLine();
}
}
in.close();
This was written in a hurry, so please pardon any errors:
String aStore = "";
String bStore = "";
String aFinal[];
String bFinal[];
try{
Scanner input = new Scanner(new File("file.txt"));
while(input.hasNextLine()){
String message = input.nextLine();
message = message.replace(" ", "");
String store[] = message.split(",");
for(int a = 0; a < store.length; a++){
if((store[a]).contains("A-"){
String t[] = (store[a]).split("-");
aStore = aStore + "_" + t[1];
}
if((store[a]).contains("B-"){
String t[] = (store[a]).split("-");
bStore = bStore + "_" + t[1];
}
}
aFinal = aStore.split("_");
bFinal = bStore.split("-");
}
input.close();
}
catch(Exception e){}
To split a line into an array of words, use this:
String words = sentence.split("[^\\w']+");
The regex [^\w'] means "not a word char or an apostrophe"
This will capture words with embedded apostrophes like "can't" and skip over all punctuation.
Edit:
A comment has raised the edge case of parsing a quoted word such as 'this' as this.
Here's the solution for that - you have to first remove wrapping quotes:
String[] words = input.replaceAll("(^|\\s)'([\\w']+)'(\\s|$)", "$1$2$3").split("[^\\w']+");
Here's some test code with edge and corner cases:
public static void main(String[] args) throws Exception {
String input = "'I', ie \"me\", can't extract 'can't' or 'can't'";
String[] words = input.replaceAll("(^|[^\\w'])'([\\w']+)'([^\\w']|$)", "$1$2$3").split("[^\\w']+");
System.out.println(Arrays.toString(words));
}
Output:
[I, ie, me, can't, extract, can't, or, can't]
Also is it possible to separate the Strings? Yes, You can split string by using this for white spaces.
String[] strSplit;
String str = "This is test for split";
strSplit = str.split("[\\s,;!?\"]+");
See String API
Moreover you can also read a text file word by word.
Scanner scan = null;
try {
scan = new Scanner(new BufferedReader(new FileReader("Your File Path")));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
while(scan.hasNext()){
System.out.println( scan.next() );
}
See Scanner API
I would recommend using an ArrayList, which handles dynamic sizing, whereas an array will require a defined size up front, which you may not know. You can always turn the list back into an array.
BufferedReader in = new BufferedReader(new FileReader("path/of/text"));
String str;
List<String> list = new ArrayList<String>();
while((str = in.readLine()) != null){
list.add(str);
}
String[] stringArr = list.toArray(new String[0]);
The simplest solution:
List<String> list = Files.readAllLines(Paths.get("path/of/text"), StandardCharsets.UTF_8);
String[] a = list.toArray(new String[list.size()]);
Note that java.nio.file.Files is since 1.7
words[i] = inputFile.nextLine();
Here you are trying to store the next line from the input file into the index i of the words array. You have not declared or assigned a value to i, so Java won't know what you're trying to do.
With standard arrays, you must assign them an initial array value consisting of an explicit number of "slots" (indexes). With a Scanner, you could count the number of lines by reading them all and discarding the values. Once you have this counter, you can initialise the String[] with the appropriate size. Finally, you can read them all again and storing them into the array.
int counter = 0;
while (inputFile.hasNext()) {
inputFile.nextLine();
counter++;
}
inputFile = new Scanner(testFile); //to get to the beginning of the file
String[] words = new String[counter];
for (int i = 0; i < counter; i++) {
words[i] = inputFile.nextLine();
}
This is very bad practice; reading the whole file merely to find its length is an overkill, and a waste of resources.
Therefore, it would be much better to use a collection type that automatically expands as you put elements into it, such as an ArrayList.
ArrayList<String> lines = new ArrayList<String>();
while (inputFile.hasNext()) {
lines.add(inputFile.nextLine());
}
But it's likely that you're assignment requires you to use both Scanner and a standard String[]. In that case, you could change the size of the String[] manually:
String[] words = new String[0];
while (inputFile.hasNext()) {
words = Arrays.copyOf(words, words.length + 1);
words[words.length - 1] = inputFile.nextLine();
}
or
String[] words = new String[0];
while (inputFile.hasNext()) {
String temp = new String[words.length + 1];
System.arraycopy(words, 0, temp, 0, words.length);
temp[temp.length - 1] = inputFile.nextLine();
words = temp;
}
ArrayList words = new ArrayList(); while (inputFile.hasNextLine()){ String word = inputFile.getNextLine(); words.add(word); }
Since you don't know how big this is, you should use an arrayList. You can then sort alphabetically or whatever you need.
There are a number of ways to do this. In order to effectively place the file contents into a Two Dimensional (2D) Array you will need to know how large your array will need to be in order to properly fit everything into it so as not to run into the problem of generating an ArrayOutOfBoundsException when you fill that array. The size of the Array needs to be established before you can place elements into it. Things to consider are:
- Is it the right text file to begin with?
- How many valid data lines are there in the file?
- How many columns are there per line?
- Are there any unwanted lines within the file (like a header line or blank lines)?
This is why using a collection mechanism like ArrayList, Map, HashMap, etc is a good way to tackle this. You can always convert that collection into an Array when your done retrieving the data.
By looking at your example file (well...the image of it :/) it looks like there is a Header Line which briefly describes what each data column in each file line is for. You didn't specify whether or not you want this to be part of your 2D Array. You also didn't specify the data type for your 2D Array, will it be Object, String, or will it be Integer?
With the above in mind we have to assume that you don't want the header line to be placed into the Array and you simply want the raw integer data values contained within each row column. This then answers the Array Data Type question....Integer (int).
Here is one way to carry out the task:
public int[][] readDataFile(String filePath) throws FileNotFoundException {
ArrayList<int[]> list;
// Try with resources...Auto closes scanner
try (Scanner sRead = new Scanner(new File(filePath))) {
list = new ArrayList<>();
String line;
int lineCounter = 0;
while (sRead.hasNextLine()) {
line = sRead.nextLine().trim();
// Skip any blank lines
if (line.equals("")) { continue; }
lineCounter++;
// Is it a valid data file?
if (lineCounter == 1 && !line.startsWith("P1")) {
// No it's not!
JOptionPane.showMessageDialog(null, "Invalid Data File!",
"Invalid File!",
JOptionPane.WARNING_MESSAGE);
return null;
}
// Skip the Header Line
else if (line.startsWith("P1")) { continue; }
// Split the incomming line and convert the
// string values to int's
String[] strArray = line.split("\\s+");
int[] intArray = new int[strArray.length];
for(int i = 0; i < strArray.length; i++) {
intArray[i] = Integer.parseInt(strArray[i]);
}
// Add to ArrayList
list.add(intArray);
}
}
// Convert the ArrayList to a 2D int Array
int[][] array = new int[list.size()][list.get(0).length];
for (int i = 0; i < list.size(); i++) {
System.arraycopy(list.get(i), 0, array[i], 0, list.get(i).length);
}
return array;
}
And to use this method you might go with:
try {
int[][] a = readDataFile("C:\\Users\\loren\\Desktop\\t\\respuestas.txt");
for (int[] a1 : a) {
System.out.println(Arrays.toString(a1));
}
} catch (FileNotFoundException ex) { ex.printStackTrace(); }
Use a list of String arrays and then convert this list into the 2D String array.
In this case, "result" will be your desired output.
Assumption: words in the input file are separated by tab
import java.io.*;
import java.util.List;
import java.util.ArrayList;
class Final {
public static void main (String [] args) throws Exception {
File file = new File ("C:\\Users\\loren\\Desktop\\t\\respuestas.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String st;
List<String[]> resultList = new ArrayList<>();
while ((st=br.readLine()) !=null) {
resultList.add(st.split("\t"));
}
String[][] result = new String[resultList.size()][resultList.get(0).length];
for(int i=0; i<resultList.size(); i++) {
result[i] = resultList.get(i);
}
}
}
How do I convert information from a text file so that its in an array, with all of the words in the text file broken up by letter into the different rows and columns?