Reading a Text File Character by Character into a 2D Array in Java

Reading text file character by character into a 2d char[][] array

If I have understood it correctly - file format is something like

4 4
FILE
WITH
SOME
INFO

Modify as below

    Scanner scanner = new Scanner(inFile);     
String[] size = scanner.nextLine().split("\\s");

char[][] array = new char[Integer.parseInt(size[0])][Integer.parseInt(size[1])];

for(int i=0; i < rows; i++) {
array[i] = scanner.nextLine().toCharArray();
}

Above code is for initialization of you char array. In order to print the same you can do something like

Arrays.deepToString(array);

Reading a text file character by character into a 2D array in Java

The simplest way to do this, in my opinion, is to first read the file line-by-line then read those lines character-by-character. By using a built-in utility, you can avoid the complexities of handling new lines because they vary by OS/Editor.

BufferedReader Docs

    BufferedReader fileInput = new BufferedReader(new FileReader("example.txt"));
String s;
while ((s = fileInput.readLine()) != null) {
for (char c : s.toCharArray()) {
//Read into array
}
}
fileInput.close();

read txt file of ascii chars into 2d array in java

I created an input file with your ASCII boat and was able to reproduce the image.

                .'|     .8
. | .8:
. | .8;: .8
. | .8;;: | .8;
. n .8;;;: | .8;;;
. M.8;;;;;: |,8;;;;;
. .,"n8;;;;;;: |8;;;;;;
. .', n;;;;;;;: M;;;;;;;;
. ,' , n;;;;;;;;: n;;;;;;;;;
. ,' , N;;;;;;;;: n;;;;;;;;;
. ' , N;;;;;;;;;: N;;;;;;;;;;
.,' . N;;;;;;;;;: N;;;;;;;;;;
.. , N6666666666 N6666666666
I , M M
---nnnnn_______M___________M______mmnnn
"-. /
~~~~~~~~~~~@@@**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

I used a List<list<Character>> to hold the ASCII matrix image.

I created two methods. The createImageMatrix method creates the List<List<Character>> image matrix. Each line of the image text file is read and put in a List<Character> line list. Each line list is put in the image matrix.

The printImageMatrix method uses a StringBuilder to construct the ASCII image for display and verification.

Here's the complete runnable code. You can ignore the first two lines of the main method. I keep all my testing resources in a resource folder. The first two lines give me the complete path to the text file in the resource folder.

import java.io.File;
import java.io.FileNotFoundException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class AsciiImage {

public static void main(String[] args) {
URL url = AsciiImage.class.getResource("/boat.txt");
String filename = url.getFile();

AsciiImage ai = new AsciiImage(filename);
List<List<Character>> imageMatrix = ai.createImageMatrix();
System.out.println(ai.printImageMatrix(imageMatrix));
}

private String filename;

public AsciiImage(String filename) {
this.filename = filename;
}

public List<List<Character>> createImageMatrix() {
List<List<Character>> imageMatrix = new ArrayList<>();

try {
Scanner input = new Scanner(new File(filename));
while (input.hasNext()) {
String s = input.nextLine();
List<Character> lineList = new ArrayList<>(s.length());
for (int index = 0; index < s.length(); index++) {
lineList.add(Character.valueOf(s.charAt(index)));
}
imageMatrix.add(lineList);
}
input.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}

return imageMatrix;
}

public String printImageMatrix(List<List<Character>> imageMatrix) {
StringBuilder builder = new StringBuilder();
for (List<Character> lineList : imageMatrix) {
for (char c : lineList) {
builder.append(c);
}
builder.append(System.lineSeparator());
}

return builder.toString();
}

}

Reading char with scanner from txt file and adding to a 2d array

Scanner.next() always returns a String. Please check https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html for more information. Before performing any operation on scan.next() e.g. scan.next().charAt(0), you should check if (scan.hasNext()) condition.

How do I read a text file into a 2D char array?

Read file contents into a string. Use x,y -> index transformation for your coordinates. Access the characters of this string as if the characters where in 2D array. See a solution to the problem "Using an array of Strings to create a 2D (map) array in Java" .

How do you convert a text file into a 2D character array?

I'm guessing your file looks something like this

##########################
#........................#
#.....###........###.....#
#......G..........G......#
#........................#
#...........E............#
#......G.........G.......#
#........G.....G.........#
#..........###...........#
#........................#
##########################

If you print the file length, you will see that the file length is 296

As Your code row = 11 and columns = 26

When you are copying to map you are copying up to 11 * 26 = 286

Try the UPDATED code below

public void readMap(String fileName) throws IOException {
BufferedReader br = new BufferedReader(new FileReader(fileName));
int lines = 0, columns = 0;
String str;
List<String> lineList = new ArrayList<>();
while ((str = br.readLine()) != null && str.length() != 0) {
lines++;
columns = Math.max(columns, str.length()); // as it's not fixed
lineList.add(str);
}
System.out.println("Row : " + lines);
System.out.println("Columns : " + columns);

char[][] map = new char[lines][columns];
for (int i = 0; i < lines; i++) {
String currentLine = lineList.get(i);
int idx = 0;
for (int j = 0; j < currentLine.length(); j++) {
map[i][j] = currentLine.charAt(idx++);
}
}
for (int r = 0; r < map.length; r++) {
for (int c = 0; c < (map[0].length); c++) {
System.out.print(map[r][c]);
}
System.out.println();
}
}

Reading a file as a 2d char array

Make sure that you're importing java.io.* (or specific classes that you need if that's what you want) to include the FileNotFoundException class. It was a bit hard to show how to fill the 2D array since you didn't specify how you want to parse the file exactly. But this implementation uses Scanner, File, and FileNotFoundException.

public AsciiArt(String filename, int nrRow, int nrCol){
this.nrRow = nrRow;
this.nrCol = nrCol;
image = new char[nrRow][nrCol];

try{
Scanner input = new Scanner(new File(filename));

int row = 0;
int column = 0;

while(input.hasNext()){
String c = input.next();
image[row][column] = c.charAt(0);

column++;

// handle when to go to next row
}

input.close();
} catch (FileNotFoundException e) {
System.out.println("File not found");
// handle it
}
}

In java, input text and put them into a two Dimensional character array

Note : this will fill character space with '*' and fill the remain cell of Array 2D with '-'.

public class twoDimensionalCharacterArray {

public static void main(String[] args) {

int row = 6, col = 7;
char[][] chars = new char[row][col];

Scanner scan = new Scanner(System.in);
System.out.print("Type in a sentence: ");
String message = scan.nextLine();
char[] messages = message.toCharArray();
int i = 0;
for (int r = 0; r < chars.length; r++) {
for (int c = 0; c < col; c++) {
if (i < messages.length) {
chars[r][c] = messages[i] == ' ' ? '*' : messages[i];
i++;
} else {
chars[r][c] = '-';
}
}
}
for (char[] x : chars) {
System.out.println(Arrays.toString(x));
}
}

}


Related Topics



Leave a reply



Submit