Load .text file in string array - java

How can I load .txt file into string array?
private void FileLoader() {
try {
File file = new File("/some.txt");
Scanner sc = new Scanner(new FileInputStream(file), "Windows-1251");
//Obviously, exception
int i = 0;
while (sc.hasNextLine()) {
morphBuffer[i] = sc.nextLine();
i++;
//Obviously, exception
}
sc.close();
} catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(null, "File not found: " + e);
return;
}
}
There is an issue with array's length, because I don't know how long my array will be.
Of course i saw this question, but there is not an array of string. I need it, because I have to work with whole text, also with null strings.
How can I load a text file into string array?

Starting with Java 7, you can do it in a single line of code:
List<String> allLines = Files.readAllLines("/some.txt", Charset.forName("Cp1251"));
If you need your data in a string array rather than a List<String>, call toArray(new Strinf[0]) on the result of the readAllLines method:
String[] allLines = Files.readAllLines("/some.txt", Charset.forName("Cp1251")).toArray(new String[0]);

Use List
private void FileLoader() {
try {
File file = new File("/some.txt");
Scanner sc = new Scanner(new FileInputStream(file), "Windows-1251");
List<String> mylist = new ArrayList<String>();
while (sc.hasNextLine()) {
mylist.add(sc.nextLine());
}
sc.close();
} catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(null, "File not found: " + e);
return;
}
}

You can use Collection ArrayList
while (sc.hasNextLine()) {
list.add(sc.nextLine());
i++;
//Obviously, exception
}
http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html

Related

How to add comma seperated string and int into two different arraylists [java]

Say I have strings and integers being read from a file and seperated by a comma and I want to add them into two different arrayLists.
hamburger,15
cheese,10
soda,15
How would I go about doing this? I intially used nextLine() to add them into one arraylist and extract the integer and erase the comma but this wasn't working for arrayLists. I also tried using nextInt() to just grab the int's but was given an exception.
public static void readFile(ArrayList items, ArrayList cost)
{
String intValue = "";
try
{
Scanner read = new Scanner(new File("Menu.txt"));
while (read.hasNext())
{
items.add(read.nextLine());
}
read.close();
for (int i = 0; i < items.size(); i++)
{
intValue = items.indexOf(i).replaceAll("[^0-9]", "");
int value = Integer.parseInt(intValue);
cost.add(value);
}
System.out.println(item);
System.out.println(cost);
}
catch(FileNotFoundException fnf)
{
System.out.println("File was not found.");
}
}
my end result would be:
items = [hamburger, cheese, soda]
cost = [15, 10, 15]
public static void readFile(List<String> items, List<Integer> costs) {
try {
Scanner read = new Scanner(new File("Menu.txt"));
while (read.hasNext()) {
String line = read.nextLine();
String[] itemsAndCosts = line.split(",");
items.add(itemsAndCosts[0]);
costs.add(Integer.parseInt(itemsAndCosts[1]));
}
read.close();
System.out.println(items);
System.out.println(costs);
} catch (FileNotFoundException fnf) {
System.out.println("File was not found.");
}
}
Use List<String> instead of ArrayList.
You can split the line on the , and then you have an array of 2 elements, item and cost. (Note: will only work if there is only one , per line). You can also use .subString(...), but for me, splitting is cleaner.
Use try-with-resources so you don't need to do .close():
try (Scanner read = new Scanner(new File("Menu.txt"))) {
while (read.hasNext()) {
String line = read.nextLine();
String[] itemsAndCosts = line.split(",");
items.add(itemsAndCosts[0]);
costs.add(Integer.parseInt(itemsAndCosts[1]));
}
System.out.println(items);
System.out.println(costs);
} catch (FileNotFoundException fnf) {
System.out.println("File was not found.");
}

Where do I place the return of a function in JAVA?

I'm trying to figure out how to make a function in JAVA that searches through a document line per line:
First I initialize the file and a reader, then convert each line to a string in an ArrayList; after that I try to check the ArrayList against a String to then return the position of the ArrayList as a string.
So for example I have a text containing:
1 - Somewhere over the rainbow
2 - Way up high.
Converted to ArrayList, if then searched for: "Somewhere"; then it should return the sentence "Somewhere over the rainbow";
Here is the code I tried; but it keeps returning 'null';
String FReadUtilString(String line) {
File file = new File(filepath);
ArrayList<String> lineReader = new ArrayList<String>();
System.out.println();
try {
Scanner sc = new Scanner(file);
String outputReader;
while (sc.hasNextLine()) {
lineReader.add(sc.nextLine());
}
sc.close();
for(int count = 0; count < lineReader.size(); count++) {
if(lineReader.get(count).contains(line)){outputReader = lineReader.get(count);}
}
} catch (Exception linereadeline) {
System.out.println(linereadeline);
}
return outputReader;
}
I refactor your code a bit, but I keep your logic, it should work for you:
String FReadUtilString(String line, String fileName){
File file = new File(fileName);
List<String> lineReader = new ArrayList<>();
String outputReader = "";
try (Scanner sc = new Scanner(file))
{
while (sc.hasNextLine()) {
lineReader.add(sc.nextLine());
}
for (int count = 0; count < lineReader.size(); count++){
if (lineReader.get(count).contains(line)){
outputReader = lineReader.get(count);
}
}
}
catch (Exception linereadeline) {
System.out.println(linereadeline);
}
return outputReader;
}
NOTE: I used the try-with-resource statement to ensure the closing of the Scanner.
A more succinct version:
String fReadUtilString(String line, String fileName) {
try (Stream<String> lines = Files.lines(Paths.get(fileName))) {
return lines.filter(l -> l.contains(line)).findFirst();
}
catch (Exception linereadeline) {
System.out.println(linereadeline); // or just let the exception propagate
}
}

How To Read A Text File Via Scanner

I am trying to read from a text file, but whenever the program gets to my while loop it just skips over it. I used a previous example I had to check to see if I did it correctly, but it doesn't seem to be working this time.
EDIT: to clarify, the while with "b++" under it is being skipped.
EDIT 2: Updated code.
public static void main(String[] args) throws FileNotFoundException {
ToDoItem td = new ToDoItem();
ToDoList tl = new ToDoList();
File file = new File("ToDoItems.txt");
Scanner ReadFile = new Scanner(file);
Scanner keyboard = new Scanner(System.in);
ArrayList<String> list = new ArrayList<>();
String inputline;
System.out.println("Welcome to the list maker!" + "\n" + "Please start typing.");
try (PrintWriter fout = new PrintWriter(new File("ToDoItems.txt"))) {
do {
System.out.println("add to the list? [y/n]");
inputline = keyboard.nextLine();
if ("y".equals(inputline)) {
fout.print(td.getDescription() + "\n");
} else {
System.out.println("Here is the list so far:");
while (ReadFile.hasNext()) {
String listString = ReadFile.nextLine();
list.add(listString);
}
}
} while ("y".equals(inputline));
} catch (FileNotFoundException e) {
System.err.println(e.getMessage());
}
System.out.println(list);
}
Ideally I want it to print a part of the Array each time it passes through the while loop. But it just ends up skipping over it.
I checked the text file itself, and it does have the information I want to print to it. Yet for some reason the scanner won't read it properly.
I guess your problem is that you are trying to read a file that you are currently using, try close the fout object before read it, something like this:
public static void main(String[] args){
File file = new File("ToDoItems.txt");
ToDoItem td = new ToDoItem();
ToDoList tl = new ToDoList();
Scanner keyboard = new Scanner(System.in);
ArrayList<String> list = new ArrayList<>();
String inputline;
System.out.println("Welcome to the list maker!" + "\n" + "Please start typing.");
try (PrintWriter fout = new PrintWriter(file)) {
// ^^ here
do {
System.out.println("add to the list? [y/n]");
inputline = keyboard.nextLine();
if ("y".equals(inputline)) {
fout.print(td.getDescription() + System.lineSeparator());
} else {
// Important line is here!
fout.close(); // <--- Close printwriter before read file
System.out.println("Here is the list so far:");
Scanner ReadFile = new Scanner(file);
while (ReadFile.hasNext()) {
String listString = ReadFile.nextLine();
list.add(listString);
}
}
} while ("y".equals(inputline));
} catch (FileNotFoundException e) {
System.err.println(e.getMessage());
}
System.out.println(list);
}
String[] stringArray = new String[b]; is problematic as your int b = 0;.
Also, it seems like you do not know how large your array will even be. I would suggest you use an ArrayList instead. That way you will not need a counter, just add to the ArrayList.
It would be better to try and catch your FileNotFoundException instead of throwing at the main but I guess you know that your file will always be there.

How to filter out info by using useDelimiter

So, what am I trying to do is I get the info from a text file,
For example, 134567H;Gabriel;24/12/1994;67;78;89
Then I display only Admin number which is the first one but not the whole line in drop down list. So here are my codes :
public static String[] readFile(){
String file = "output.txt";
ArrayList <String> studentList = new ArrayList <String> ();
try{
FileReader fr = new FileReader(file);
Scanner sc = new Scanner(fr);
sc.useDelimiter(";");
while(sc.hasNextLine()){
studentList.add(sc.nextLine());
}
fr.close();
}catch(FileNotFoundException exception){
System.out.println("File " + file + " was not found");
}catch(IOException exception){
System.out.println(exception);
}
return studentList.toArray(new String[studentList.size()]);
}
And this is how I populate the drop down list :
public void populate() {
String [] studentList ;
studentList = Question3ReadFile.readFile();
jComboBox_adminNo.removeAllItems();
for (String str : studentList) {
jComboBox_adminNo.addItem(str);
}
}
However, my problem now is the options in drop down list is showing the whole line from the text file. It is not showing the admin number only. I tried with useDelimiter already. Am I supposed to use that?
Any help would be appreciated. Thanks in advance.
Rince help check.
public class Question3ReadFile extends Question3 {
private String adminNo;
public Question3ReadFile(String data) {
String[] tokens = data.split(";");
this.adminNo = tokens[0];
}
public static String[] readFile(){
String file = "output.txt";
ArrayList <String> studentList = new ArrayList <String> ();
try{
FileReader fr = new FileReader(file);
Scanner sc = new Scanner(fr);
while(sc.hasNextLine()){
studentList.add(new Question3ReadFile(sc.nextLine()));
}
fr.close();
}catch(FileNotFoundException exception){
System.out.println("File " + file + " was not found");
}catch(IOException exception){
System.out.println(exception);
}
return studentList.toArray(new String[studentList.size()]);
}
hasNext and next instead of hasNextLine and nextLine
public static void main(String[] args) {
String input = " For example, 134567H;Gabriel;24/12/1994;67;78;89";
Scanner scanner = new Scanner(input);
scanner.useDelimiter(";");
String firstPart = null;
while(scanner.hasNext()){
firstPart = scanner.next();
break;
}
String secondPart = input.split(firstPart)[1].substring(1);
System.out.println(firstPart);
System.out.println(secondPart);
scanner.close();
}
Don't use delimiter in this case. I suggest to make a Student object out of the line.
studentList.add(new Student(sc.nextLine));
and have the Student class:
public class Student {
private final String adminNo;
public Student(String data) {
String[] tokens = data.split(";");
this.adminNo = tokens[0];
}
public String getAdminNo() {
return adminNo;
}
}
and then you just read the fields you need later (student.getAdminNo()) for example.
This approach is much prettier and easier to extend later.
upd: simplistic approach
Or don't bother with stupid OO and just do this:
studentList.add(sc.nextLine.split(";")[0]);

Java reading a file into an ArrayList?

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);

Categories

Resources