Printing All Values via File Writer - java

I want to print all the letter that the user will input but the thing is, my program only prints the last value that the user will input, and only the last value is recorded in Ascii.txt. It should look like this
for example : the user input A,B,c,C
I want also to delete the comma but I can't :(
output in "Ascii.txt" should be:
A = 65
B = 66
c = 99
C = 67
please dont laugh at me because im still a student and new to programming, thank you very much
import java.io.*;
public class NewClass2{
public static void main(String args[]) throws IOException{
BufferedReader buff = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please Enter letters separated by comma: ");
String str = buff.readLine();
for ( int i = 0; i < str.length(); ++i )
{
char c = str.charAt(i);
int j = (int) c;
System.out.println(c +" = " + j);
{
try
{
FileWriter fstream = new FileWriter("Ascii.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write(c+" = "+j);
out.close();
}catch (Exception e){
}
}
}
}
}

The Problem is that you close and re-open the FileStream for each character you want to dump to your ASCII-File. Thus, your file will be emptied before writing a character. Just move the creation and closing of the stream outside the loop.
BufferedReader buff = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please Enter letters separated by comma: ");
String str = buff.readLine();
BufferedWriter out = null;
try
{
FileWriter fstream = new FileWriter("Ascii.txt");
out = new BufferedWriter(fstream);
for ( int i = 0; i < str.length(); ++i )
{
char c = str.charAt(i);
int j = c;
System.out.println(c + " = " + j);
out.write(c + " = " + j);
}
}
catch ( Exception e )
{
;
}
finally
{
if ( out != null )
{
out.close();
}
}
In order to remove the commas from the output I would suggest to use String.split():
//...
String[] splittedStr = str.split(",");
for ( int i = 0; i < splittedStr.length; i++ )
{
if ( splittedStr[i].length() > 0 )
{
char c = splittedStr[i].charAt(0);
int j = c;
out.write(c + " = " + j);
}
}
//...

You only write in your file AFTER your loop on str.
BufferedWriter out;
try{
FileWriter fstream = new FileWriter("Ascii.txt");
out = new BufferedWriter(fstream);
for ( int i = 0; i < str.length(); ++i ){
char c = str.charAt(i);
int j = (int) c;
System.out.println(c +" = " + j);
out.write(c+" = "+j);
} catch ...{
...
} finally {
if (out!=null)
out.close();
}

As pointed out, you're closing the stream every time you writes to the file. Maybe you were looking for the flush() method.
Just to complement, if you're using Java 7, you can use the try with resources (so you don't have to bother with closing it):
BufferedReader buff = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please Enter letters separated by comma: ");
String str = buff.readLine();
try( BufferedWriter out = new BufferedWriter(new FileWriter("Ascii.txt"))){
//Using split
String[] splitted = str.split(",");
for(String s : splitted){
char c = s.charAt(0);
int j = c;
out.write(c + " = " + j);
}
}catch(Exception E){
//You really should catch specific exceptions here.
}

Related

java BufferedReader & Writer doesn't work as expected

What I was trying to do was to read a mnist train file, and express it's first digit in eleven digits, and keep other same.
So 3,1,4,6 ... to ,0,0,0,1,0,0,0,0,0,0,1,4,6... (there's "" at first digit so total 11 digits)
I thought it's an easy job but it wasn't.
import java.io.*;
public class T {
public static void main(String[] args){
File file = new File("./src/dataset/mnist_train.csv");
File wfile = new File("./src/dataset/conv_mnist_train2.txt");
try{
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
BufferedWriter fileWriter = new BufferedWriter(new FileWriter(wfile));
String line;
String[] numbers;
int g = 0, cnt = 0, cnt2 = 0;
while ((line = bufferedReader.readLine()) != null) {
cnt2++;
numbers = line.split(",");
for(String i : numbers){
if(g == 0){
for(int j=0; j<10; ++j) {
if(j == Integer.parseInt(i)) fileWriter.write("," + 1);
else{ fileWriter.write("," + 0); cnt++;}
}
g++;
}
else {fileWriter.write("," +i); cnt++;}
}
fileWriter.newLine();
System.out.println(numbers.length + " " + cnt + " " + cnt2);
g = 0; cnt = 0;
}
}catch(Exception e){
e.printStackTrace();
}
}
}
g, cnt, cnt2 are numbers I used for debugging but I didn't find any problem here; it naturally converted each lines with 785 letters into new lines with 795 letters.
import java.io.*;
public class Tes {
public static void main(String[] args){
File file = new File("./src/dataset/conv_mnist_train2.txt");
try{
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
String line;
int g = 0;
while ((line = bufferedReader.readLine()) != null) {
g++;
String[] N = line.split(",");
if(N.length != 795){
System.out.println(N.length + " " + g);
for(String i : N) System.out.print(i + " ");
System.out.println();
}
}
}catch(Exception e){
e.printStackTrace();
}
}
}
But what happened is that when I run my second code, which shouldn't print anything, printed result and said my 59994th row data is only consisted of 311 letters. But from my first code, I confirmed that my 59994th row has 795 letters. I don't know what's going on here.
Also I tried to use FileWriter and FileReader instead of BufferedWriter & Reader, but it didn't solve problem. Could somebody tell me what's going on, and how to fix this?
The problem was that I didn't close the reader/writer. Didn't know it could end up in serious error.

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

Dealing with txt file via split(), says Nullpointerexception

I know there are many similar questions here, but I still can't solve it. I can get all the results that I want. However, in the end, it still shows nullpointerexception. I don't know why. can anyone help?
public class PointGenterate {
public static void main(String[] args) throws FileNotFoundException {
// TODO Auto-generated method stub
try{
File file = new File("123.txt");
double[] pointsid = new double[10];
String[] data = null;
for(int i = 0; i <10; i++){
double rn = (int)(Math.random()*120);
System.out.println(rn);
pointsid[i] = rn;
}
//read file
InputStreamReader rs = new InputStreamReader(new FileInputStream(file));//create input stream reader object
BufferedReader br = new BufferedReader(rs);
String line = "";
line = br.readLine();
//
File write = new File("output.KML");
write.createNewFile();
BufferedWriter out = new BufferedWriter(new FileWriter(write));
while(line != null){
line = br.readLine();
if(line==" "){
System.out.print("empty");
}else{
data = line.split(",|:|[|]");
}
for(int i = 0; i < data.length; i++){
data[i] = data[i].trim();
System.out.println(data[i] + "num" + i);
}
if(data.length > 15){
double id = Double.parseDouble(data[4]);
for(int i = 0; i <10; i++){
if(id == pointsid[i]){
data[10] = data[10].substring(0, data[10].length()-2);
data[15] = data[15].substring(1,data[15].length());
data[16] = data[16].substring(0, data[16].length()-6);
out.write(data[8]+" "+ data[10]+ " " + data[13] + data[15] + data[16]+ "\r\n");
out.flush();
}
}
}
//System.out.println(line);
}
out.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
the txt file format is like
{ "type": "Feature", "properties": { "id": 126.000000, "osm_id": 4851918786.000000, "name": "Moray House Library", "type": "library" }, "geometry": { "type": "Point", "coordinates": [ -3.180841771200988, 55.950622362732418 ] } },
this is one line. I have many lines, and actually this is just a test code. if it works. i want to write it as a method in a javaseverlet class. get the string coordinates and return it to my JS font-end.
There's a few issues with your code. In this section:
InputStreamReader rs = new InputStreamReader(new FileInputStream(file));//create input stream reader object
BufferedReader br = new BufferedReader(rs);
String line = "";
line = br.readLine(); // here you read the first line in the file
//
File write = new File("output.KML");
write.createNewFile();
BufferedWriter out = new BufferedWriter(new FileWriter(write));
while(line != null){ // here you check that it's not null (it's not, you read the first line OK)
line = br.readLine(); // here you read the second line (there is no second line, now line is null)
if(line==" "){ // now you check if the line is a space character (this is wrong for 2 reasons, that's not how you compare strings, and a space character is not an empty string)
System.out.print("empty");
}else{
data = line.split(",|:|[|]"); // here you call split() on line but line is null
}
When you checked if the string was empty, you did line == " " which is wrong for 2 reasons. First you cannot use == to compare strings - read this question for details on why not. Second, " " is a string that contains a space character. "" is an empty string.
When you want to check if a string is empty you can do it like this:
line.equals("")
or like this:
line.isEmpty()
Here's your code with a few small changes so that it runs without throwing an exception.
public class PointGenterate {
public static void main(String[] args) throws Exception {
try {
File file = new File("123.txt");
double[] pointsid = new double[10];
String[] data = null;
for(int i = 0; i < 10; i++){
double rn = (int)(Math.random()*120);
System.out.println(rn);
pointsid[i] = rn;
}
//read file
InputStreamReader rs = new InputStreamReader(new FileInputStream(file));//create input stream reader object
BufferedReader br = new BufferedReader(rs);
String line = "";
//
File write = new File("output.KML");
write.createNewFile();
BufferedWriter out = new BufferedWriter(new FileWriter(write));
while((line = br.readLine()) != null){ // read the line and check for null
if(line.isEmpty()) { // is the line equal to the empty string?
System.out.print("empty");
} else {
data = line.split(",|:|[|]");
}
for(int i = 0; i < data.length; i++){
data[i] = data[i].trim();
System.out.println(data[i] + "num" + i);
}
if(data.length > 15){
double id = Double.parseDouble(data[4]);
for(int i = 0; i <10; i++){
if(id == pointsid[i]){
data[10] = data[10].substring(0, data[10].length()-2);
data[15] = data[15].substring(1,data[15].length());
data[16] = data[16].substring(0, data[16].length()-6);
out.write(data[8]+" "+ data[10]+ " " + data[13] + data[15] + data[16]+ "\r\n");
out.flush();
}
}
}
//System.out.println(line);
}
out.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}

Java Reading 2D array in from file, numbers separated by comma

This is some code that I found to help with reading in a 2D Array, but the problem I am having is this will only work when reading a list of number structured like:
73
56
30
75
80
ect..
What I want is to be able to read multiple lines that are structured like this:
1,0,1,1,0,1,0,1,0,1
1,0,0,1,0,0,0,1,0,1
1,1,0,1,0,1,0,1,1,1
I just want to essentially import each line as an array, while structuring them like an array in the text file.
Everything I have read says to use scan.usedelimiter(","); but everywhere I try to use it the program throws straight to the catch that replies "Error converting number". If anyone can help I would greatly appreciate it. I also saw some information about using split for the buffered reader, but I don't know which would be better to use/why/how.
String filename = "res/test.txt"; // Finds the file you want to test.
try{
FileReader ConnectionToFile = new FileReader(filename);
BufferedReader read = new BufferedReader(ConnectionToFile);
Scanner scan = new Scanner(read);
int[][] Spaces = new int[10][10];
int counter = 0;
try{
while(scan.hasNext() && counter < 10)
{
for(int i = 0; i < 10; i++)
{
counter = counter + 1;
for(int m = 0; m < 10; m++)
{
Spaces[i][m] = scan.nextInt();
}
}
}
for(int i = 0; i < 10; i++)
{
//Prints out Arrays to the Console, (not needed in final)
System.out.println("Array" + (i + 1) + " is: " + Spaces[i][0] + ", " + Spaces[i][1] + ", " + Spaces[i][2] + ", " + Spaces[i][3] + ", " + Spaces[i][4] + ", " + Spaces[i][5] + ", " + Spaces[i][6]+ ", " + Spaces[i][7]+ ", " + Spaces[i][8]+ ", " + Spaces[i][9]);
}
}
catch(InputMismatchException e)
{
System.out.println("Error converting number");
}
scan.close();
read.close();
}
catch (IOException e)
{
System.out.println("IO-Error open/close of file" + filename);
}
}
I provide my code here.
public static int[][] readArray(String path) throws IOException {
//1,0,1,1,0,1,0,1,0,1
int[][] result = new int[3][10];
BufferedReader reader = new BufferedReader(new FileReader(path));
String line = null;
Scanner scanner = null;
line = reader.readLine();
if(line == null) {
return result;
}
String pattern = createPattern(line);
int lineNumber = 0;
MatchResult temp = null;
while(line != null) {
scanner = new Scanner(line);
scanner.findInLine(pattern);
temp = scanner.match();
int count = temp.groupCount();
for(int i=1;i<=count;i++) {
result[lineNumber][i-1] = Integer.parseInt(temp.group(i));
}
lineNumber++;
scanner.close();
line = reader.readLine();
}
return result;
}
public static String createPattern(String line) {
char[] chars = line.toCharArray();
StringBuilder pattern = new StringBuilder();;
for(char c : chars) {
if(',' == c) {
pattern.append(',');
} else {
pattern.append("(\\d+)");
}
}
return pattern.toString();
}
The following piece of code snippet might be helpful. The basic idea is to read each line and parse out CSV. Please be advised that CSV parsing is generally hard and mostly requires specialized library (such as CSVReader). However, the issue in hand is relatively straightforward.
try {
String line = "";
int rowNumber = 0;
while(scan.hasNextLine()) {
line = scan.nextLine();
String[] elements = line.split(',');
int elementCount = 0;
for(String element : elements) {
int elementValue = Integer.parseInt(element);
spaces[rowNumber][elementCount] = elementValue;
elementCount++;
}
rowNumber++;
}
} // you know what goes afterwards
Since it is a file which is read line by line, read each line using a delimiter ",".
So Here you just create a new scanner object passing each line using delimter ","
Code looks like this, in first for loop
for(int i = 0; i < 10; i++)
{
Scanner newScan=new Scanner(scan.nextLine()).useDelimiter(",");
counter = counter + 1;
for(int m = 0; m < 10; m++)
{
Spaces[i][m] = newScan.nextInt();
}
}
Use the useDelimiter method in Scanner to set the delimiter to "," instead of the default space character.
As per the sample input given, if the next row in a 2D array begins in a new line, instead of using a ",", multiple delimiters have to be specified.
Example:
scan.useDelimiter(",|\\r\\n");
This sets the delimiter to both "," and carriage return + new line characters.
Why use a scanner for a file? You already have a BufferedReader:
FileReader fileReader = new FileReader(filename);
BufferedReader reader = new BufferedReader(fileReader);
Now you can read the file line by line. The tricky bit is you want an array of int
int[][] spaces = new int[10][10];
String line = null;
int row = 0;
while ((line = reader.readLine()) != null)
{
String[] array = line.split(",");
for (int i = 0; i < array.length; i++)
{
spaces[row][i] = Integer.parseInt(array[i]);
}
row++;
}
The other approach is using a Scanner for the individual lines:
while ((line = reader.readLine()) != null)
{
Scanner s = new Scanner(line).useDelimiter(',');
int col = 0;
while (s.hasNextInt())
{
spaces[row][col] = s.nextInt();
col++;
}
row++;
}
The other thing worth noting is that you're using an int[10][10]; this requires you to know the length of the file in advance. A List<int[]> would remove this requirement.

Categories