Read in mulitple Files and Array List - java

I want to save every line in my files into an Array List.
When i have only one file it works fine, but if i readin multiple files the first line of every file are all saved in the same Array...
Code:
public static void main(String[] args)
{
File folder = new File("\\Documents\\Files");
File[] listOfFiles = folder.listFiles();
for(File file : listOfFiles) {
dosomething(file);
}
}
public static void dosomething(File file)
{
try {
List<String[]> lines = new ArrayList<>();
BufferedReader reader = new BufferedReader(new FileReader(file));
String[] tmp;
String line;
while ((line = reader.readLine()) != null) {
tmp = line.split("\n");
if (tmp.length > 0) {
lines.add(tmp);
}
}
reader.close();
System.out.println(lines.get(0));
}
....
}
Result:
[Ljava.lang.String;#15db9742
[Ljava.lang.String;#6d06d69c
[Ljava.lang.String;#7852e922
In my folder "files" i have 3 file.txt and every file contains lines of text.
So i wanted do save every line of every file into a new Array. But why i have no 3 Lines saved instead of 1 one?
Can someone helpme?
Thanks
Now i tried it this way:
public static String [] stringArr;
public static void main(String[] args)
{
File folder = new File("\\Documents\\Files");
File[] listOfFiles = folder.listFiles();
for(File file : listOfFiles) {
dosomething(file);
}
List<String> lines = new ArrayList<>();
for(String s : stringArr)
{
lines.add(s);
}
for(String t : lines)
{
System.out.println(t);
}
}
public static void dosomething(File file)
{
try {
List<String> list= new ArrayList<>();
BufferedReader in = new BufferedReader(new FileReader(file));
String str;
while((str = in.readLine()) != null){
list.add(str);
}
stringArr = list.toArray(new String[0]);
}
reader.close();
}
Result: If do a for-loop of stringArr in the dosomthing methode, every contant of each file perfectly saved in my stringArr.... but now if i do the for loop in the Main-methode i just get the content of one file back...

First of all you don't need a list of arrays to store the lines but can be simply stored in a String.
so
List<String> lines=new ArrayList<String>();
BufferedReader reader = new BufferedReader(new FileReader(file));
String line;
while ((line = reader.readLine()) != null) {
lines.add(tmp);
}
will suffice the need of storing the lines from file into your arraylist.
For printing the lines from the list you can just iterate over your list and print them.
for(String string : lines ){
System.out.println(string);
}
EDIT after OP edited the question
1.Why to again use String[] stringArr instead use it as a list and add lines to it. I see your whole intention is to store the lines of all three files in a list(or array) which is used to print them all at once
public List<String> globalList;
public static void main(String[] args)
{
globalList=newArrayList<String>();
File folder = new File("\\Documents\\Files");
File[] listOfFiles = folder.listFiles();
for(File file : listOfFiles) {
dosomething(file);
}
for(String t : globalList) {
System.out.println(t);
}
}
public static void dosomething(File file)
{
try {
BufferedReader in = new BufferedReader(new FileReader(file));
String str;
while((str = in.readLine()) != null){
globalList.add(str);
}
}
reader.close();
}

Related

How to save integers from a .txt file into an array?

So i have an array int[] numbers = {1,2};
But i want the 1,2 to be removed and replaced with numbers from an txt file.
I can see the numbers from the files in the console with this method:
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()]);
}
public static void testFileArrayProvider() throws IOException {
algo1 fap = new algo1();
String[] lines = fap
.readLines("D:/Users/XXX/workspace/abc/src/abc1/Filename123");
for (String line : lines) {
System.out.println(line);
}
}
NOw i need to save them in the array. BUt how? xd
Thx guys
This should work:
// In your case this is already populated
String[] lines = new String[] {"123", "4567"};
// Easier to work with lists first
List<Integer> results = new ArrayList<>();
for (String line : lines) {
results.add(Integer.parseInt(line));
}
// If you really want it to be int[] for some reason
int[] finalResults = new int[results.size()];
for (int i = 0; i < results.size(); i++) {
finalResults[i] = results.get(i);
}
// This is only to prove it worked
System.out.println(Arrays.toString(finalResults));
In Java-8, you can shorten it to
int[] finalResults = Arrays.stream(lines).mapToInt(Integer::parseInt).toArray();

Saving text file content to a linked list

I am trying to save the contents of a word file line by line into a LinkedList.
What am I doing wrong? The console is showing that it is definatley reading the file but not saving its contents?
public class SpellCheck {
LinkedList<String> lines = new LinkedList();
boolean suggestWord ;
public static void main(String[] args) throws java.io.IOException{
System.out.println("Welcome to the spellchecker");
LinkedList<String> list = new LinkedList<String>();
try {
File f = new File("input/dictionary.txt");
FileReader r = new FileReader(f);
BufferedReader reader = new BufferedReader(r);
String line = null;
String word = new String();
while((line = reader.readLine()) != null)
{
list.add(word);
word = new String();
}
reader.close();
}catch(IOException e) {
e.printStackTrace();
}
for(int i = 0; i<list.size();i++){
System.out.println(list.get(i));
}
}
}
You are adding word which is an empty string instead of adding line which you read from file:
String word = new String();
while((line = reader.readLine()) != null)
{
list.add(word);
^^^^^
word = new String();
}
It should be:
while((line = reader.readLine()) != null) {
list.add(line);
}

2 Dimensional ArrayList not Printing Properly

I am creating a function to print a mase, which is stored in a 2 Dimensional ArrayList<ArrayList<String>>. However, the function instead prints out a large portion of blank space. I am attempting to first iterate through each ArrayList<String> and then iterate through each String element inside the nested ArrayList<String>s. I am creating the ArrayList<ArrayList<String>> from reading a file.
Here is the file:
XXXXXXXXSOOOOXXXXXX
XXXXXXXXXXXXOXXXXXX
XXXXXXXXXXXXOXXXXXX
XXXXXXXXXXXXOXXXXXX
XXXXXXXOOOOOXXXXXX
XXXXXXXOXXXXXXXXXXX
XXXXXXXEXXXXXXXXXXX
Here is where I create it:
String fileName = "maze.txt";
String line = null;
ArrayList<ArrayList<String>> lines = new ArrayList<ArrayList<String>>();
// Setup FileReader, BufferedReader, and LineReader
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader);
// Get all the lines inside the maze file
while ((line = bufferedReader.readLine()) != null)
{
ArrayList<String> lineList = new ArrayList<String>();
for (int i = 0; i < line.length(); i++)
{
lineList.add(line.substring(i, i));
}
lines.add(lineList);
}
Here is my function:
public static void printMase(ArrayList<ArrayList<String>> lines)
{
for (ArrayList<String> row: lines)
{
for (String elem: row)
{
System.out.println(elem);
}
}
}
There are just some minor mistakes in your code. Make the following changes.
// This is adding a blank space
lineList.add(line.substring(i, i));
To
// This will add a single character
lineList.add(line.substring(i, i+1));
and modify printMase(ArrayList<ArrayList<String>> lines)
public static void printMase(ArrayList<ArrayList<String>> lines)
{
for (ArrayList<String> row: lines)
{
for (String elem: row)
{
// Using print so each character is on the same line
System.out.print(elem);
}
// Now use println to end the line
System.out.println();
}
}
Full code looks like:
public static void main(String[] args) throws Exception {
String fileName = "maze.txt";
String line = null;
ArrayList<ArrayList<String>> lines = new ArrayList<>();
// Setup FileReader, BufferedReader, and LineReader
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader);
// Get all the lines inside the maze file
while ((line = bufferedReader.readLine()) != null) {
ArrayList<String> lineList = new ArrayList<>();
for (int i = 0; i < line.length(); i++) {
// Adds a single character
lineList.add(line.substring(i, i+1));
}
lines.add(lineList);
}
printMase(lines);
}
public static void printMase(ArrayList<ArrayList<String>> lines)
{
for (ArrayList<String> row: lines)
{
for (String elem: row)
{
// Using print so each character is on the same line
System.out.print(elem);
}
// Now use println to end the line
System.out.println();
}
}
Results:
XXXXXXXXSOOOOXXXXXX
XXXXXXXXXXXXOXXXXXX
XXXXXXXXXXXXOXXXXXX
XXXXXXXXXXXXOXXXXXX
XXXXXXXOOOOOXXXXXXX
XXXXXXXOXXXXXXXXXXX
XXXXXXXEXXXXXXXXXXX
Woops, I realized that I was adding blank space during initialization. I updated my code such that it was adding the actual characters:
String fileName = "maze.txt";
String line = null;
ArrayList<ArrayList<String>> lines = new ArrayList<ArrayList<String>>();
// Setup FileReader, BufferedReader, and LineReader
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader);
while ((line = bufferedReader.readLine()) != null)
{
ArrayList<String> lineList = new ArrayList<String>();
for (int i = 0; i < line.length(); i++)
{
lineList.add(Character.toString(line.charAt(i)));
}
lines.add(lineList);
}

Reading a file object in Java

How do you read a file object in java?
File file= new File(filePathName);
if (file.exists()){
filesArrayList.add(file);
}
Depending on the number of processors threads are sent:
a file and a starting (lower bound) and end (upper bound) to read.
File inputFile= (File)filesArrList.get(i);
BufferedInputStream bis= new BufferedInputStream(new FileInputStream (inputFile));
while ((line=bis.readLine())!=null) {
System.out.println(line);
}
Is it possible to read the files in the arraylist?
1 : You can read files stored in ArrayList through the following way.
2 : Yes it is also possible to read files stored in array list.
public class ReadingFiles {
BufferedReader br;
ArrayList<File> list = new ArrayList<>();
ReadingFiles() {
list.add(new File((getClass().getResource("file1.txt")).getPath()));
readFile(list.get(0));
list.add(new File((getClass().getResource("file2.txt")).getPath()));
readFile(list.get(1));
}
public void readFile(File file) {
try {
br = new BufferedReader(new FileReader(file));
String line = br.readLine();
while (line != null) {
System.out.println(line);
line = br.readLine();
}
br.close();
} catch (Exception ex) {
System.out.println("Sorry");
}
}
public static void main(String[] args){
new ReadingFiles();
}
}

Java - What is the best way to make a method that reads a file and outputs an array of what the file contains?

I am learning Java and in order to learn more about Java IO I am making a program to read a file path and return an array that contains everything from the file. I didn't want to specify that the data had to be integers so I've been working in strings. I'm running into an issue when I try to run a method returning an array. Is there a better way I should be writing this code?
import java.io.*;
public class OrganizeIO
{
public static void main(String[] args) throws Exception
{
String sampleData[] = readFile("C://Users/Tweak/workspace/FileIO/resources/data.txt");
int i = 0;
while(sampleData[i] != null)
{
System.out.print(sampleData[i]);
i++;
}
}
public static String[] readFile(String file) throws IOException
{
BufferedReader br = null;
String currentLine;
String[] data;
br = new BufferedReader(new FileReader(file));
int i = 0;
while((currentLine = br.readLine()) != null)
{
System.out.println(currentLine);
currentLine = data[i];
i++;
}
return data[];
}
}
You're not storing anything in data, not to mention you haven't even initialized it (which results in a compilation error). You should be using a List anyway, since you don't know how many lines you are going to read beforehand:
List<String> data = new ArrayList<String>();
while ((currentLine = br.readLine()) != null) {
data.add(currentLine);
}
return data.toArray(new String[data.size()]); // or just return the list?
Also, don't forget to close your BufferedReader:
br.close();
Well for one it looks like you while loop should be
while((currentLine = br.readLine()) != null)
{
System.out.println(currentLine);
data[i] = currentLine;
i++;
}
because you are returning nothing
I think you can work with the class Scanner to read the file and store it in a List.
// Open the file
Scanner scanner = new Scanner(new File("C:\\Users\\Tweak\\workspace\\FileIO\\resources\\data.txt"));
// Read the file line by line
List<String> result = new ArrayList<String>();
while (scanner.hasNext())
{
result.add(scanner.nextLine());
}
scanner.close();
// If you want an array
String sampleData[] = result.toArray(new String[result.size()]);
Since you don't know how many lines you get, storing the read lines directly in an array is inappropriate, better take a List implementation for that:
public static List<String> readFile (File file, String encoding) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), encoding));
List<String> result = new LinkedList<String>();
String line;
while ((line = reader.readLine()) != null) {
result.add(line);
}
return result;
}
Usage:
public static void main (String[] args) throws IOException {
File file = new File("C://Users/Tweak/workspace/FileIO/resources/data.txt");
List<String> lines = readFile(file, "UTF-8");
for (String line : lines) {
System.out.println(line);
}
}
You can of course convert the List into a String array later, if that's what you want:
String[] linesArray = lines.toArray(new String[0]);

Categories