Copying a text file into a 2D char array in java - java

I'm working on reading a text file that contains an 5x6 character big ascii image. Here's what i've done so far:
...
Scanner fileReader = null;
try{
File file = new File(fileName);
fileReader = new Scanner(file);
int offset = 0;
char [][] pic = new char[5][6];
while (fileReader.hasNextLine()){
for (int u = 0; u < row; u++){
for (int i = 0; i < col; i++){
String line = fileReader.nextLine();
pic[u][i] = line.charAt(offset++);
}
}
return pic;
}
fileReader.close();
}
catch(Exception e){
System.out.println(e.getMessage());
}...
This gives me a "no line found" message. I'm wondering if the scanner i use to ask the user the name of the file is a part of the problem. Here's what that looks like:
System.out.println("Hello! I load files.");
System.out.println("Please, enter file name:");
Scanner reader = new Scanner(System.in);
String fileName = reader.nextLine();
I've tried to close the reader after but it didn't change anything. Any help is much appreciated.

Several things :
First, you are attempting to read a line for each index of your array (that is row*col times).
Second, you should only read a line by row.
You may replace your whole while loop with this :
for (int u = 0; u < row && fileReader.hasNextLine(); u++) {
String line = fileReader.nextLine();
for (int i = 0; i < col; i++) {
pic[u][i] = line.charAt(offset++);
}
offset = 0;
}
return pic;
Also , you probably want to reset the value of offset after each processed "row".

Scanner fileReader = new Scanner (new File("file.txt"));
int i = 0;
char[][] pic = new char[5][];
while (fileReader.hasNextLine()){
String line = fileReader.nextLine();
pic[i] = line.toCharArray();
i++;
}
fileReader.close();
I tried it with seuqnce and worked:
Scanner fileReader = new Scanner(System.in);
System.out.println(fileReader.nextLine());
fileReader.close();
fileReader = new Scanner (new File("file.txt"));
int i = 0;
char[][] pic = new char[5][];
while (fileReader.hasNextLine()){
String line = fileReader.nextLine();
pic[i] = line.toCharArray();
System.out.println(line);
i++;
}
fileReader .close();
output:
sadsadd sadsadd
sadasdasdasdsad sadasdasdsadsa sadasdasdsadsadsa dAS dASd
Process finished with exit code 0

Related

Filling a matrix with content from file

I'm getting an error on my code. The goal is to add the contents of a file to a matrix.Then ill eventually need to parse it to add it to a graph so that i can eventually perform a depth-first search on it. But until then i need to figure this error out. I can't figure out what exactly is causing the error. so any help would be nice.
Here is the error im getting:
Exception in thread "AWT-EventQueue-0" java.util.NoSuchElementException
at java.base/java.util.Scanner.throwFor(Scanner.java:937)
at java.base/java.util.Scanner.next(Scanner.java:1478)
at DelivA.<init>(DelivA.java:53)
at Prog340.actionPerformed(Prog340.java:120
Here is the class i wrote.
public DelivA(File in, Graph gr) {
inputFile = in;
g = gr;
// Get output file name.
String inputFileName = inputFile.toString();
String baseFileName = inputFileName.substring(0, inputFileName.length() - 4); // Strip off ".txt"
String outputFileName = baseFileName.concat("_out.txt");
outputFile = new File(outputFileName);
if (outputFile.exists()) { // For retests
outputFile.delete();
}
try {
output = new PrintWriter(outputFile);
} catch (Exception x) {
System.err.format("Exception: %s%n", x);
System.exit(0);
}
// --------------------------------Deliverable
// A-------------------------------------------//
FileReader f1 = null;
int c = 0;
int r = 0;
try {
f1 = new FileReader(inputFileName);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Scanner scanner = new Scanner(f1);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String splitLine[] = line.split(" ");
c = splitLine.length;
r++;
}
String[][] matrix = new String[c][r];
#SuppressWarnings("resource")
Scanner s1 = new Scanner(f1);
for (int row = 0; row < matrix.length; row++) {
String words = s1.next(); // will scan each row of the file
for (int col = 0; col < matrix[row].length; col++) {
char ch = words.charAt(col); // will put each character into array
matrix[row][col] = String.valueOf(ch);
}
}
}
}
Your problem is probably here:
String words = s1.next():
You are not verifying if there is any line available.
You should do something like this:
...
Scanner s1 = new Scanner(f1);
for (int row = 0; row < matrix.length; row++) {
if (scanner.hasNextLine()){
String words = s1.next(); // will scan each row of the file
...
Of course you should rethink the code logic accordingly...

How to get data from a CSV file and place it in a list

I want to read data from a CSV file in Java and then put this data into a list. The data in the CSV is put into rows which looks like:
Data, 32, 4.3
Month, May2, May 5
The code I have currently only prints the [32].
ArrayList<String> myList = new ArrayList<String>();
Scanner scanner = new Scanner(new File("\\C:\\Users\\Book1.csv\\"));
scanner.useDelimiter(",");
while(scanner.hasNext()){
myList.add(scanner.next());
for (int i = 0; i <= myList.size(); i++) {
System.out.println(myList.toString());
}
scanner.close();
}
Maybe this code can help you, maybe this code is different from yours, you use arrayList while I use regular array.
Example of the data:
Farhan,3.84,4,72
Rajab,2.98,4,72
Agil,2.72,4,72
Alpin,3.11,4,73
Mono,3,6,118 K
imel,3.97,7,132
Rano,2.12,6,110
Kukuh,4,1,22
Placing data on each row in a csv file separated by commas into the array of each index
int tmp = 0;
String read;
Mahasiswa[] mhs = new Mahasiswa[100];
BufferedWriter outs;
BufferedReader ins;
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
Scanner input = new Scanner(System.in);
try {
ins = new BufferedReader(new FileReader("src/file.csv"));
tmp = 0;
while ((read = ins.readLine()) != null) {
String[] siswa = read.split(",");
mhs[tmp] = new Mahasiswa();
mhs[tmp].nama = siswa[0];
mhs[tmp].ipk = Float.parseFloat(siswa[1]);
mhs[tmp].sem = Integer.parseInt(siswa[2]);
mhs[tmp].sks = Integer.parseInt(siswa[3]);
tmp++;
i++;
}
ins.close();
} catch (IOException e) {
System.out.println("Terdapat Masalah: " + e);
}
Print the array data
tmp = 0;
while (tmp < i) {
System.out.println(mhs[tmp].nama + "\t\t" +
mhs[tmp].ipk + "\t\t" +
mhs[tmp].sem + "\t\t" +
mhs[tmp].sks);
tmp++;
}
ArrayList<String> myList = new ArrayList<String>();
try (Scanner scanner = new Scanner(new File("C:\\Users\\Book1.csv"))) {
//here at your code there are backslashes at front and end of the path that was the
//main reason you are not able to read csv file
scanner.useDelimiter(",");
while (scanner.hasNext()) {
myList.add(scanner.next());
}
for (int i = 0; i < myList.size(); i++) { //remember index is always equal to "length - 1"
System.out.println(myList);
}
} catch (Exception e) {
e.printStackTrace();
}
you also did not handle the FileNotFoundException
Hope this helps:)

How to read a String from a txt file and store it into a char array java

So I am trying to read a txt file into a char array and print out the contents, but I only get the first index of the String to print out. The contents of the file are "EADBC"
public static void main(String args[]) throws IOException
{
char [] correctAnswers = new char [20];
String [] studentName = new String[5];
char [][] studentAnswers = new char [20][20];
Scanner sc = new Scanner (System.in);
System.out.println ("Welcome to the Quiz Grading System \n");
System.out.println ("Please Enter the name of the file that contains the correct answers");
Scanner answerFile = new Scanner (new File (sc.next() + ".txt"));
int i = 0;
int fillLvl = 0;
String answer;
while (answerFile.hasNext() )
{
answer = answerFile.next();
correctAnswers[i] = answer.charAt(i);
i++;
fillLvl = i;
}
answerFile.close();
System.out.println("Correct Answers: ");
for(int j = 0; j < fillLvl; j++)
{
System.out.println(correctAnswers[j]);
}
To read from a text file and convert into an array:
File file = new File("C:\\Users\\dell\\Desktop\\rp.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String st;
char[] string1={};
int size = 0;
//reads the string and converts into array
while ((st = br.readLine()) != null){
string1 = st.toCharArray();
size = st.length();
}
//For printing
for(int i=0;i<size;i++){
System.out.println(string1[i]);
}
Inside while loop use like this..
while (answerFile.hasNext() )
{
answer = answerFile.next();
int j = 0;
while(answer != null && !answer.isEmpty() && j < answer.length()){
correctAnswers[i] = answer.charAt(j);
i++;
j++;
fillLvl = i;
}
}
It is always recommended to use FileReader, BufferedReader to perform file operation;
Here you go, read once and print them simple. Don't read them into a string and split them and again to a char.
BufferedReader reader = new BufferedReader(
new InputStreamReader(new FileInputStream("\\path\\to\\file.extension"))
);
int c;
while((c = reader.read()) != -1) {
char character = (char) c;
System.out.println(character);
}
reader.close();

Reading a text file into a char[][] array in Java

I am trying to fill a char[][] array from a text file and I cannot seem to figure out how to do it. I've tried to use .toCharArray() but it doesn't seem to work. If you can give any insight on how to make this work that would be awesome!
String filename = "ArrayHW2.txt";
int numTests = 6;
char[][] testAnswers = new char[50][5];
char[] key = new char[4];
Scanner input = null;
try
{
input = new Scanner(new File(filename));
}
catch(FileNotFoundException e)
{
System.out.println("Error Opening File");
System.exit(1);
}
for(int row = 0; row < testAnswers.length; row++)
{
for(int col = 0; col < testAnswers[row].length; col++)
{
testAnswers[row][col] = input.next().toCharArray();
}
}
input.close();
The basic problem is that you are trying to assign a character array to something was meant to hold a character. You might think of char[] type as storing the location in memory where characters are recorded, and a char type as the character itself.
When you call toCharArray() on a String, the return type is char[]. It looks like you expect this array to have a single character, like the A, B, C, or D of a multiple-choice test. You could get the first (and only?) character of that array with something like ...toCharArray()[0], but this is wasteful because a new array is created, and characters are copied into it from the source string. It's simpler to use the getCharAt() method on the String directly.
String filename = "ArrayHW2.txt";
char[][] testAnswers = new char[50][5];
try (Scanner input = new Scanner(Paths.get(filename))) {
for(int row = 0; row < testAnswers.length; row++) {
for(int col = 0; col < testAnswers[row].length; col++) {
String token = r.next();
if (token.length() != 1)
throw new IllegalArgumentException("Answers must be one character");
testAnswers[row][col] = token.charAt(0);
}
}
} catch (IOException ex) {
System.err.println("Error reading file: " + ex.getMessage());
System.exit(1);
}
String filename = "ArrayHW2.txt";
int numTests = 6;
char[][] testAnswers = new char[50][5];
//char[] key = new char[4];
Scanner input = null;
try
{
input = new Scanner(new File(filename));
}
catch(FileNotFoundException e)
{
System.out.println("Error Opening File");
System.exit(1);
}
int counter = 0;
while(scanner.hasNext())
{
copyString(testAnswers[counter], scanner.nextLine());
}
input.close();
its been a while i haven't code in java and im not sure about the methods but consider it a pseudo code .
you can use this copy :
void copyString(char[] arr, String x)
{
int size = x.length();
for (int i=0; i<size; i++){
arr[i] = x.CharAt(i);
}

Overwriting a line in java txt file

So I have created this method which at the end displays the whole line because i am displaying the array after converting and editing it. So my Question is how can i know overwrite the array to the same line i grabbed it from. thanks in advance and here is my code.
public void getData(String path, String accountNumber) {
try {
FileInputStream fis = new FileInputStream(path);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
System.out.println("Please Enter the Deposit amount That you would like to add.");
Scanner sn = new Scanner (System.in);
int add = sn.nextInt();
String str;
while ((str = br.readLine()) != null) {
if (str.contains(accountNumber)) {
String[] array = str.split(" ");
int old = Integer.parseInt(array[3]);
int Sum= old + add;
String Sumf = Integer.toString(Sum);
array[3] = Sumf;
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);}
break;
}
}
} catch (Exception ex) {
System.out.println(ex);
}
}
i am using string accountNumber to grab the specific line that i need. after getting the line i am changing it to an array while splitting the index with str.split(" "); . After that i know that i need to edit index number [3]. so i do so and then i put it back into the array. the final thing i need to do is to right the array back now.
You can keep track of the input from the file you are reading and write it back with the modified version.
public void getData(String path, String accountNumber) {
try {
FileInputStream fis = new FileInputStream(path);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
System.out.println("Please Enter the Deposit amount That you would like to add.");
Scanner sn = new Scanner (System.in);
int add = sn.nextInt();
String line; // current line
String input = ""; // overall input
while ((line = br.readLine()) != null) {
if (line.contains(accountNumber)) {
String[] array = line.split(" ");
int old = Integer.parseInt(array[3]);
int Sum= old + add;
String Sumf = Integer.toString(Sum);
array[3] = Sumf;
// rebuild the 'line' string with the modified value
line = "";
for (int i = 0; i < array.length; i++)
line+=array[i]+" ";
line = line.substring(0,line.length()-1); // remove the final space
}
// add the 'line' string to the overall input
input+=line+"\n";
}
// write the 'input' String with the replaced line OVER the same file
FileOutputStream fileOut = new FileOutputStream(path);
fileOut.write(input.getBytes());
fileOut.close();
} catch (Exception ex) {
System.out.println(ex);
}
}
This is how i understand the question that you have a file you will read it line by line and will make some changes and want to write it again at the same position. Create a new temp file and write the contents to the temp file, if changed write the changed result if not write it as it is.
And at last rename the temp to your original file name

Categories