Reading File into a char[] array or arraylist - java

I need to read text from the user and create an array which contains characters so that I can run them through a FSM. However, I can't seem to get the buffered reader to agree with a non-string type of input. Any advice? I also don't know if I should be using an array or arraylist
static ArrayList<Character> StringList = new ArrayList<Character>();
static char[] data;
public static void main(String[] args){
InputStreamReader ISR = new InputStreamReader (System.in);
BufferedReader BR = new BufferedReader(ISR);
try{
String sCurrentChar;
while((sCurrentChar=BR.readLine())!=null){
for(int i= 0; i<sCurrentChar.length(); i++)
StringList.add(sCurrentChar.charAt(i));
}
for(int i =0; i<StringList.size(); i++){
System.out.println(StringList.get(i));
}
} catch(IOException e){
e.printStackTrace();
}
}

Maybe something like the following could work for you, if you want to read raw byte data, maybe using them later as characters. This might be a better approach than reading input line at a time.
import java.io.DataInputStream;
import java.io.EOFException;
import java.io.IOException;
import java.util.Arrays;
public class a {
public static void main(String[] args){
DataInputStream d = new DataInputStream(System.in);
int[] bytes = new int[256];
try {
int b;
int l = 0;
while((b = d.readByte()) > 0) {
bytes[l++] = b;
if((l % 256) == 0)
bytes = Arrays.copyOf(bytes, (l + 256));
}
} catch(EOFException e) {
// end-of-file
} catch(IOException e) {
System.err.println("AIEEEE: " + e);
System.exit(-1);
}
for(int i = 0; bytes[i] > 0; i++) System.out.print((char)bytes[i]);
System.exit(0);
}
}
The way arrays are treated here is probably a fine example how one should not do it, but then again, this is more about reading bytes/unsigned characters of data than efficiently processing arrays.

Related

PrintWriter creates empty file

I have the following problem I want to read a file and shift each letter down by 3 positions in the alphabet. The caesar cipher works correctly and I can print it, but whenever I am trying to pass it on to a new file with PrintWriter the file remains empty.
import java.io.IOException;
import java.io.File;
import java.io.PrintWriter;
import java.util.Scanner;
public static char[] encrypt (int offset, char [] charArray) {
char [] cryptArray = new char [charArray.length];
for (int i = 0; i < charArray.length; i++) {
int crypt = (charArray[i] + offset);
cryptArray[i] = (char) (crypt);
}
return cryptArray;
}
public static void main(String[] args) {
String text = "";
StringBuilder convert = new StringBuilder();
try {
File file = new File ("C:\\PATH\\file.txt");
Scanner input = new Scanner (file);
while (input.hasNextLine()) {
text = input.nextLine();
convert = new StringBuilder (text);
char [] arr = text.toCharArray();
char [] newArr = encrypt(3, arr);
for (int i = 0; i < newArr.length; i++) {
convert.append(newArr[i]).toString();
}
}
input.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
// write file
File outFile = new File ("C:\\PATH\\newfile.txt");
PrintWriter printer = new PrintWriter (outFile);
printer.print(convert);
printer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
remove convert = new StringBuilder (text); in your loop. It's overwriting your data in the previous loop

How to count occurrence of Polish characters in .txt file

I have to prepare a .txt file and count how many times each character of alphabet occurs in the file. I've found a very nice piece of code, but unfortunately, it doesn't work with Polish characters like ą,ę,ć,ó,ż,ź. Even though I put them in the array, for some reason they are not found in the .txt file so the output is 0.
Does anyone know why? Maybe I should count them differently, with "Switch" or something similar.
Before anyone asks - yes, the .txt file is saved with UTF-8 :)
public static void main(String[] args) throws FileNotFoundException {
int ch;
BufferedReader reader;
try {
int counter = 0;
for (char a : "AĄĆĘÓBCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray()) {
reader = new BufferedReader(new FileReader("C:\\Users\\User\\Desktop\\pan.txt"));
char toSearch = a;
counter = 0;
try {
while ((ch = reader.read()) != -1) {
if (a == Character.toUpperCase((char) ch)) {
counter++;
}
}
} catch (IOException e) {
System.out.println("Error");
e.printStackTrace();
}
System.out.println(toSearch + " occurs " + counter);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
Looks like your problem related to encoding and default system charset
try to change reader variable to this
InputStreamReader reader = new InputStreamReader(new FileInputStream("C:\\Users\\User\\Desktop\\pan.txt"), "UTF-8");
try this:
I suggest that you use NIO and this code I have written for you using NIO, RandomAccessFile and MappedByteBuffer that is faster:
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.util.HashMap;
import java.util.Map;
public class FileReadNio
{
public static void main(String[] args) throws IOException
{
Map<Character, Integer> charCountMap = new HashMap<>();
RandomAccessFile rndFile = new RandomAccessFile
("c:\\test123.txt", "r");
FileChannel inChannel = rndFile.getChannel();
MappedByteBuffer buffer = inChannel.map(FileChannel.MapMode.READ_ONLY, 0, inChannel.size());
buffer.load();
for (int i = 0; i < buffer.limit(); i++)
{
char c = (char) buffer.get();
if (charCountMap.get(c) != null) {
int cnt = charCountMap.get(c);
charCountMap.put(c, ++cnt);
}
else
{
charCountMap.put(c, 1);
}
}
for (Map.Entry<Character,Integer> characterIntegerEntry : charCountMap.entrySet()) {
System.out.printf("char: %s :: count=%d", characterIntegerEntry.getKey(), characterIntegerEntry.getValue());
System.out.println();
}
buffer.clear();
inChannel.close();
rndFile.close();
}
}

Generated integers to a binary file

I have assignment question I could not get the final answer.
the question was :
Write a program that will write 100 randomly generated
integers to a binary file using the writeInt(int) method in
DataOutputStream. Close the file. Open the file using a
DataInputStream and a BufferedInputStream. Read the integer
values as if the file contained an unspecified number (ignore
the fact that you wrote the file) and report the sum and average
of the numbers.
I believe I done first part of the question which is (write into file), but I don't know how to report the sum.
so far that what I have
import java.io.*;
public class CreateBinaryIO {
public static void main(String [] args)throws IOException {
DataOutputStream output = new DataOutputStream(new FileOutputStream("myData.dat"));
int numOfRec = 0 + (int)(Math.random()* (100 - 0 +1));
int[] counts = new int[100];
for(int i=0;i<=100;i++){
output.writeInt(numOfRec);
counts[i] += numOfRec;
}// Loop i closed
output.close();
}
}
This ReadBinaryIO class:
import java.io.*;
public class ReadBinaryIO {
public static void main(String [] args)throws IOException {
DataInputStream input = new DataInputStream (new BufferedInputStream(new FileInputStream("myData.dat")));
int value = input.readInt();
System.out.println(value + " ");
input.close();
}
}
Try to divide the problem in parts to organice your code, don't forget to flush the OutputStream before you close it.
package javarandomio;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Random;
public class JavaRandomIO {
public static void main(String[] args) {
writeFile();
readFile();
}
private static void writeFile() {
DataOutputStream output=null;
try {
output = new DataOutputStream(new FileOutputStream("myData.txt"));
Random rn = new Random();
for (int i = 0; i <= 100; i++) {
output.writeInt(rn.nextInt(100));
}
output.flush();
output.close();
} catch (Exception e) {
System.out.println(e.getMessage());
} finally{
try{
output.close();
}catch(Exception e){
System.out.println(e.getMessage());
}
}
}
private static void readFile() {
DataInputStream input=null;
try {
input = new DataInputStream(new FileInputStream("myData.txt"));
int cont = 0;
int number = input.readInt();
while (true) {
System.out.println("cont =" + cont + " number =" + number);
if (input.available() == 4) {
break;
}
number = input.readInt();
cont++;
}
input.close();
} catch (Exception e) {
System.out.println(e.getMessage());
} finally{
try{
input.close();
}catch(Exception e){
System.out.println(e.getMessage());
}
}
}
}
int numOfRec = 0 + (int)(Math.random()* (100 - 0 +1));
That's not generating a random number. Look into java.util.Random.nextInt().
int[] counts = new int[100];
for(int i=0;i<=100;i++){
output.writeInt(numOfRec);
counts[i] += numOfRec;
}// Loop i closed
That wil actually break because you are using i<=100 instead of just i<100 but I'm not sure why you are populating that array to begin with? Also, that code just writes the same number 101 times. The generation of that random number needs to be within the loop so a new one is generated each time.
As far as reading it back, you can loop through your file by using a loop like this:
long total = 0;
while (dataInput.available() > 0) {
total += dataInput.readInt();
}
Try below code where you are trying to read one integer:
DataInputStream input = new DataInputStream (new BufferedInputStream(new FileInputStream("myData.dat")));
int sum = 0;
for(int i =0; i<=100; i++){
int value = input.readInt();
sum += value;
}
System.out.println(value + " ");
input.close();
Or if you want to dynamically set the lenght of the for loop then
create a File object on myData.dat file and then divide the size of file with 32bits
File file = new File("myData.dat");
int length = file.length() / 32;
for(int i =0; i <= length;i++)
So far I submit the assignment and I think I got.
/** Munti ... Sha
course code (1047W13), assignment 5 , question 1 , 25/03/2013,
This file read the integer values as if the file contained an unspecified number (ignore
the fact that you wrote the file) and report the sum and average of the numbers.
*/
import java.io.*;
public class ReadBinaryIO {
public static void main(String [] args)throws ClassNotFoundException, IOException {
//call the file to read
DataInputStream input = new DataInputStream (new BufferedInputStream(new FileInputStream("myData.dat")));
// total to count the numbers, count to count loops process
long total = 0;
int count = 0;
System.out.println("generator 100 numbers are ");
while (input.available() > 0) {
total += input.readInt();
count ++;
System.out.println(input.readInt());
}
//print the sum and the average
System.out.println("The sum is " + total);
System.out.println("The average is " + total/count);
input.close();
}
}
CreateBinaryIO Class:
import java.io.*; import java.util.Random;
public class CreateBinaryIO { //Create a binary file public static
void main(String [] args)throws ClassNotFoundException, IOException {
DataOutputStream output = new DataOutputStream(new
FileOutputStream("myData.dat"));
Random randomno = new Random();
for(int i=0;i<100;i++){ output.writeInt(randomno.nextInt(100)); }// Loop i closed output.close(); } }

Converting CSV File to Java - Copied in Backwards

I previously asked a question about converting a CSV file to 2D array in java. I completely rewrote my code and it is almost reworking. The only problem I am having now is that it is printing backwards. In other words, the columns are printing where the rows should be and vice versa. Here is my code:
int [][] board = new int [25][25];
String line = null;
BufferedReader stream = null;
ArrayList <String> csvData = new ArrayList <String>();
stream = new BufferedReader(new FileReader(fileName));
while ((line = stream.readLine()) != null) {
String[] splitted = line.split(",");
ArrayList<String> dataLine = new ArrayList<String>(splitted.length);
for (String data : splitted)
dataLine.add(data);
csvData.addAll(dataLine);
}
int [] number = new int [csvData.size()];
for(int z = 0; z < csvData.size(); z++)
{
number[z] = Integer.parseInt(csvData.get(z));
}
for(int q = 0; q < number.length; q++)
{
System.out.println(number[q]);
}
for(int i = 0; i< number.length; i++)
{
System.out.println(number[i]);
}
for(int i=0; i<25;i++)
{
for(int j=0;j<25;j++)
{
board[i][j] = number[(j*25) + i];
}
}
Basically, the 2D array is supposed to have 25 rows and 25 columns. When reading the CSV file in, I saved it into a String ArrayList then I converted that into a single dimension int array. Any input would be appreciated. Thanks
so you want to read a CSV file in java , then you might wanna use OPEN CSV
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import au.com.bytecode.opencsv.CSVReader;
public class CsvFileReader {
public static void main(String[] args) {
try {
System.out.println("\n**** readLineByLineExample ****");
String csvFilename = "C:/Users/hussain.a/Desktop/sample.csv";
CSVReader csvReader = new CSVReader(new FileReader(csvFilename));
String[] col = null;
while ((col = csvReader.readNext()) != null)
{
System.out.println(col[0] );
//System.out.println(col[0]);
}
csvReader.close();
}
catch(ArrayIndexOutOfBoundsException ae)
{
System.out.println(ae+" : error here");
}catch (FileNotFoundException e)
{
System.out.println("asd");
e.printStackTrace();
} catch (IOException e) {
System.out.println("");
e.printStackTrace();
}
}
}
and you can get the related jar file from here

Read from a file in Java

Does anybody know how to properly read from a file an input that looks like this:
0.12,4.56 2,5 0,0.234
I want to read into 2 arrays in Java like this:
a[0]=0.12
a[1]=2
a[2]=0;
b[0]=4.56
b[1]=5
b[2]=0.234
I tried using scanner and it works for input like 0 4 5 3.45 6.7898 etc but I want it for the input at the top with the commas.
This is the code I tried:
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class IFFTI {
public static int size=0;
public static double[] IFFTInputREAL= new double[100];
public static double[] IFFTInputIMAG= new double[100];
static int real=0;
static int k=0;
public static void printarrays(){
for(int k=0;k<size;k++){
System.out.print(IFFTInputREAL[k]);
System.out.print(",");
System.out.print(IFFTInputIMAG[k]);
System.out.print("\n");
}
}
public static void readIFFT(String fileName){
try {
Scanner IFFTI = new Scanner(new File(fileName));
while (IFFTI.hasNextDouble()) {
if(real%2==0){
IFFTInputREAL[k] = IFFTI.nextDouble();
real++;
}
else{
IFFTInputIMAG[k] = IFFTI.nextDouble();
real++;
k++;}
}
try{
size=k;
}catch(NegativeArraySizeException e){}
} catch (FileNotFoundException e) {
System.out.println("Unable to read file");
}
}
}
I think this will do what you want:
String source = "0.12,4.56 2,5 0,0.234";
List<Double> a = new ArrayList<Double>();
List<Double> b = new ArrayList<Double>();
Scanner parser = new Scanner( source ).useDelimiter( Pattern.compile("[ ,]") );
while ( parser.hasNext() ) {
List use = a.size() <= b.size() ? a : b;
use.add( parser.nextDouble() );
}
System.out.println("A: "+ a);
System.out.println("B: "+ b);
That outputs this for me:
A: [0.12, 2.0, 0.0]
B: [4.56, 5.0, 0.234]
You'll obviously want to use a File as a source. You can use a.toArray() if you want to get it into a double[].
You will have to read the complete line.
String line = "0.12,4.56 2,5 0,0.234"; //line variable will recieve the line read
Then.. you split the line on the commas or the spaces
String[] values = line.split(" |,");
This will result in an array like this: [0.12, 4.56, 2, 5, 0, 0.234]
Now, just reorganize the contents between the two order arrays.
Reading from a file in Java is easy:
http://www.exampledepot.com/taxonomy/term/164
Figuring out what to do with the values once you have them in memory is something that you need to figure out.
You can read it one line at a time and turn it into separate values using the java.lang.String split() function. Just give it ",|\\s+" as the delimiter and off you go:
public class SplitTest {
public static void main(String[] args) {
String raw = "0.12,4.56 2,5 0,0.234";
String [] tokens = raw.split(",|\\s+");
for (String token : tokens) {
System.out.println(token);
}
}
}
EDIT Oops, this is not what you want. I don't see the logic in the way of constructing the arrays you want.
Read the content from the file
Split the string on spaces. Create for each element of the splitted array an array.
String input = "0.12,4.56 2,5 0,0.234";
String parts[] = input.split(" ");
double[][] data = new double[parts.length][];
Split each string on commas.
Parse to a double.
for (int i = 0; i < parts.length; ++i)
{
String part = parts[i];
String doubles[] = part.split(",");
data[i] = new double[doubles.length];
for (int j = 0; j < doubles.length; ++j)
{
data[i][j] = Double.parseDouble(doubles[j]);
}
}
File file = new File("numbers.txt");
BufferedReader reader = null;
double[] a = new double[3];
double[] b = new double[3];
try {
reader = new BufferedReader(new FileReader(file));
String text = null;
if ((text = reader.readLine()) != null) {
String [] nos = text.split("[ ,]");
for(int i=0;i<nos.length/2;i++){
a[i]=Double.valueOf(nos[2*i]).doubleValue();
b[i]=Double.valueOf(nos[2*i+1]).doubleValue();
}
}
for(int i=0;i<3;i++){
System.out.println(a[i]);
System.out.println(b[i]);
}
} catch (FileNotFoundException e) {
} catch (IOException e) {
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
}
}

Categories

Resources