How to put a large text file in to Array? - java

I have a large text file. I want to put every character in the text file, in to Character array. I use this code to put it.
List<String> set = new ArrayList<String>();
BufferedReader bf = new BufferedReader(new FileReader(file_path));
String check_line=bf.readLine();
while(check_line!=null){
set.add(check_line);
check_line=bf.readLine();
}
ArrayList<Character> charr = new ArrayList<Character>();
for(int j=0;j<set.size();++j){
String str=set.get(j);
for (int x = 0; x < str.length(); x ++){
charr.add(str.charAt(x));
}}
return charr;
But it takes long time.Is there any efficient way to do this?

You can use for each line
char[] x = str.toCharArray();

With Java 8:
public static void main(final String[] args) throws IOException {
final Path file = Paths.get("path", "to", "file");
final Character[] characters = toCharacters(file);
}
public static Character[] toCharacters(final Path file) throws IOException {
try (final Stream<String> lines = Files.lines(file)) {
return lines.flatMapToInt(String::chars).
mapToObj(x -> (char) x).
toArray(Character[]::new);
}
}
More efficient coding wise, and fewer intermediate collections created. Not sure it will be much faster however as this involves file IO which is very slow.

Why do you use a list of Strings as a temp variable and don't directly store to your Character List?
ArrayList<Character> charr = new ArrayList<Character>();
String check_line=bf.readLine();
while(check_line!=null){
for(char c : check_line.toCharArray())
charr.add(c);
check_line=bf.readLine();
}
return charr;

Just concatenate the line into one string and then convert them to an char array.
public char[] extractCharArray(String fileName) {
char[] charArray = null;
try(BufferedReader bf = new BufferedReader(new FileReader(fileName))) {
StringBuilder completeFileString = new StringBuilder();
String check_line=bf.readLine();
while(check_line!=null){
completeFileString = completeFileString.append(check_line);
check_line=bf.readLine();
}
charArray = completeFileString.toString().toCharArray();
} catch(IOException ex) {
//Handle the exception
}
return charArray;
}

Related

How to read each line of a textfile into a 2D array in Java

I am trying to create a login system in Java and I have saved admin information in a text file in this format:
Hannah,Joshua,Female,373ac,admin123
Leena,Kevin,Female,3283c,admin123
The fourth index (373ac) is their username and fifth (admin123) is the password. Each admin will get a new username and a separate line in the file.
Each time an admin logs in, they will input their name and the program should search through the file with the line that starts with their name and compare the username and password, so they can log in. I think the best way is a 2D array. I have this code so far but it's not reading it as a 2D array but just one array with all the lines. Like this:
[Hannah,Joshua,Female,373ac,admin123,Leena,Kevin,Female,3283c,admin123]
Can you please help me out?
public class ReadFile {
public static void main(String[] args) throws Exception {
BufferedReader bufReader = new BufferedReader(new FileReader("Admin.txt"));
ArrayList<String> listofLines = new ArrayList<>();
String line = bufReader.readLine();
while (null != (line = in.readLine())) {
listofLines.add(line);
}
bufReader.close();
int [][] map = new int[bufReader.size()][];
int q = 0;
for (int i = 0; i < map.length; q++) {
String[] rooms = bufReader.get(i).split(",");
map[i] = new int[rooms.length];
for (int w = 0; w < rooms.length; w++) {
map[q][w] = Integer.parseInt(rooms[w]);
}
System.out.println(Arrays.toString(map[q]));
}
}
}
You can use Files.lines() to read the file as a Stream<String>.
static String[][] readFileAs2DArray(String fileName) throws IOException {
try (Stream<String> stream = Files.lines(Path.of(fileName), Charset.defaultCharset())) {
return stream
.map(line -> line.split(","))
.toArray(String[][]::new);
}
}
public static void main(String[] args) throws IOException {
String[][] result = readFileAs2DArray("Admin.txt");
for (String[] line : result)
System.out.println(Arrays.toString(line));
}
output:
[Hannah, Joshua, Female, 373ac, admin123]
[Leena, Kevin, Female, 3283c, admin123]
You're populating listofLines but never using it
Instead of iterating based on bufReader, why not utilize listofLines?
Also, why are you using both i and q as indexes? One seems sufficient
Edit: The int[][] array should also be String[][]
String [][] map = new String[listofLines.size()][];
for (int i = 0;i<map.length;i++){
String[] rooms = listofLines.get(i).split(",");
map[i] = new int[rooms.length];
for(int w = 0; w<rooms.length;w++){
map[i][w] = rooms[w];
}
System.out.println(Arrays.toString(map[i]));
}
Also, if you want to make your code more succinct
String [][] map = new String[listofLines.size()][];
for (int i = 0;i<map.length;i++){
map[i] = listofLines.get(i).split(",");
System.out.println(Arrays.toString(map[i]));
}
For your bufReader try changing the code to this
String line = bufReader.readLine();
while (line != null) {
listofLines.add(line);
line = bufReader.readLine();
}

Filling each slot of an array with a line (String) from a text file

I have a text file list of thousands of String (3272) and I want to put them each into a slot of an Array so that I can use them to be sorted out. I have the sorting part done I just need help putting each line of word into an array. This is what I have tried but it only prints the last item from the text file.
public static void main(String[] args) throws IOException
{
FileReader fileText = new FileReader("test.txt");
BufferedReader scan = new BufferedReader (fileText);
String line;
String[] word = new String[3272];
Comparator<String> com = new ComImpl();
while((line = scan.readLine()) != null)
{
for(int i = 0; i < word.length; i++)
{
word[i] = line;
}
}
Arrays.parallelSort(word, com);
for(String i: word)
{
System.out.println(i);
}
}
Each time you read a line, you assign it to all of the elements of word. This is why word only ends up with the last line of the file.
Replace the while loop with the following code.
int next = 0;
while ((line = scan.readLine()) != null) word[next++] = line;
Try this.
Files.readAllLines(Paths.get("test.txt"))
.parallelStream()
.sorted(new ComImpl())
.forEach(System.out::println);

Java,problems with decrypting file

My code doesn't work correctly, I'm trying to decrypt a message but instead I get something like , 0, 3, ,, , 5, 7, <, ;, , ;, 9, ,, (, 4, , , -, ,, ), (, , �, ￸]
Please help me find where am I am wrong:
public class WorkInFile {
public static void main(String[] args) throws IOException {
FileInputStream encoded=new FileInputStream("C://Games//encoded.txt");//contains ƪÄÖØÐîÃÜÙäÌÊÛÓÕÒáÄßÕÍǨ³¾êÉàÝâÝãƒâÝäìÚÇäÖçÅáâÄÄÌØÐƭèÑØǑÚÚŲã¨
FileInputStream coded = new FileInputStream("C://Games//code.txt");//contains icbakwtbxxvcelsmjpbochqlltowxhlhvhyywsyqraargpdsycikmgeakonpiwcqmofwms
String text = encoded.toString();
String text2=coded.toString();
char[] chars=text.toCharArray();
char[] chars2=text2.toCharArray();
int index=0;
char[] res=new char[text.length()];
for (char aChar : chars) {
for (char c : chars2) {
res[index] = (char) (aChar - c);
}
index++;
}
String result= Arrays.toString(res);
System.out.println(result);
}
}
Files.readAllBytes(Paths.get("file-path"))
Java now offers a beautiful one-liner for reading file content.
Here is the working code for fetching file content as a string:
// WorkInFile.java
import java.nio.file.*;
public class WorkInFile {
public static void main(String[] args) {
try {
String text = new String(Files.readAllBytes(Paths.get("encoded.txt")));
System.out.println("Encoded.txt = " + text);
String text2 = new String(Files.readAllBytes(Paths.get("code.txt")));
System.out.println("code.txt = " + text2);
} catch (Exception ex) {
System.out.println(ex.toString());
}
}
}
If the expected message is in Japanese and it talks about Soviet data, this code is for you.
You must use a BufferedReader for read the file and a StringBuilder for build a String with what the BufferedReader extracts from the file.
public static void main(String args[]) {
String text;
String text2;
try {
Path encodedPath = Paths.get("C://Games//encoded.txt");
File encodedFile = new File(String.valueOf(encodedPath));
Path codedPath = Paths.get("C://Games//code.txt");
File codedFile = new File(String.valueOf(codedPath));
StringBuilder codedBuilder = new StringBuilder();
StringBuilder encodedBuilder = new StringBuilder();
try (
FileInputStream encoded = new FileInputStream(encodedFile.getAbsolutePath());
FileInputStream coded = new FileInputStream(codedFile.getAbsolutePath())
) {
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(coded))) {
String line;
while ((line = bufferedReader.readLine()) != null){
codedBuilder.append(line);
}
text = codedBuilder.toString();
}
try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(encoded))){
String line;
while ((line = bufferedReader.readLine()) != null){
encodedBuilder.append(line);
}
text2 = encodedBuilder.toString();
}
char[] chars = text.toCharArray();
char[] chars2 = text2.toCharArray();
int index = 0;
char[] res = new char[text.length()];
for (char aChar : chars) {
for (char c : chars2) {
res[index] = (char) (aChar - c);
}
index++;
}
String result = Arrays.toString(res);
System.out.println(result);
}
}
catch (IOException e) {
e.printStackTrace();
}
}
Let me know if that's what you wanted !
I think your problem lies out here:
String text = encoded.toString();
String text2=coded.toString();
You may refer to documentation to reach out that:
public String toString()
Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.
The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `#', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:
getClass().getName() + '#' + Integer.toHexString(hashCode())
Returns:
a string representation of the object.
So, toString() returns the representation of FileInputStream not the content of the stream.

How to read integers from a file that are separated with semi colon?

So in my codes, I am trying to read a file that is like:
100
22
123;22
123 342;432
but when it outputs it would include the ";" ( ex. 100,22,123;22,123,342;432} ).
I am trying to make the file into an array ( ex. {100,22,123,22,123...} ).
Is there a way to read the file, but ignore the semicolons?
Thanks!
public static void main(String args [])
{
String[] inFile = readFiles("ElevatorConfig.txt");
for ( int i = 0; i <inFile.length; i = i + 1)
{
System.out.println(inFile[i]);
}
System.out.println(Arrays.toString(inFile));
}
public static String[] readFiles(String file)
{
int ctr = 0;
try{
Scanner s1 = new Scanner(new File(file));
while (s1.hasNextLine()){
ctr = ctr + 1;
s1.next();
}
String[] words = new String[ctr];
Scanner s2 = new Scanner(new File(file));
for ( int i = 0 ; i < ctr ; i = i + 1){
words[i] = s2.next();
}
return words;
}
catch(FileNotFoundException e)
{
return null;
}
}
public static String[] readFiles(String file)
{
int ctr = 0;
try{
Scanner s1 = new Scanner(new File(file));
while (s1.hasNextLine()){
ctr = ctr + 1;
s1.next();
}
String[] words = new String[ctr];
Scanner s2 = new Scanner(new File(file));
for ( int i = 0 ; i < ctr ; i = i + 1){
words[i] = s2.next();
}
return words;
}
catch(FileNotFoundException e)
{
return null;
}
}
Replace this by
public static String[] readFiles(String file) {
List<String> retList = new ArrayList<String>();
Scanner s2 = new Scanner(new File(file));
for ( int i = 0 ; i < ctr ; i = i + 1){
String temp = s2.next();
String[] tempArr = se.split(";");
for(int k=0;k<tempArr.length;k++) {
retList.add(tempArr[k]);
}
}
return (String[]) retList.toArray();
}
Use regex. Read the entire file into a String (read each token as a String and append a blank space after each token in the String) and then split it at blank spaces and semi colons.
String x <--- contains all contents of the file
String[] words = x.split("[\\s\\;]+");
The contents of words[] are:
"100", "22", "123", "22", "123", "342", "432"
Remember to parse them to int before using as numbers.
Simple way to use BufferedReader Read line by line then split by ;
public static String[] readFiles(String file)
{
BufferedReader br = new BufferedReader(new FileReader(file)))
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
String allfilestring = sb.toString();
String[] array = allfilestring.split(";");
return array;
}
You can use split() to split the string into array according to your requirement using regex.
String s; // string you have read from the file
String[] s1 = s.split(" |;"); // s1 contains the strings separated by space and ";"
Hope it helps
Keep the code for counting the size of the array.
I would just change the way you input your values.
for (int i = 0; i < ctr; i++) {
words[i] = "" + s1.nextInt();
}
Another option is to replace all non digit characters in your complete file string with a space. That way any non number character is ignored.
BufferedReader br = new BufferedReader(new FileReader(file)))
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
line = br.readLine();
}
String str = sb.toString();
str = str.replaceAll("\\D+"," ");
Now you have a string with numbers separated by spaces, we can tokenize them into number strings.
String[] final = str.split("\\s+");
then convert to int datatypes.

The first element discarded while sorting text file using arrays in java

I have this code to sort a text file using arrays in java, but it always discard the first line of the text while sorting.
Here is my code:
import java.io.*;
public class Main {
public static int count(String filename) throws IOException {
InputStream is = new BufferedInputStream(new FileInputStream(filename));
try {
byte[] c = new byte[1024];
int count = 0;
int readChars = 0;
while ((readChars = is.read(c)) != -1) {
for (int i = 0; i < readChars; ++i) {
if (c[i] == '\n') {
++count;
}
}
}
return count;
} finally {
is.close();
}
}
public static String[] getContents(File aFile) throws IOException {
String[] words = new String[count(aFile.getName()) + 1];
BufferedReader input = new BufferedReader(new FileReader(aFile));
String line = null; //not declared within while loop
int i = 0;
while ((line = input.readLine()) != null) {
words[i] = line;
i++;
}
java.util.Arrays.sort(words);
for (int k = 0; k < words.length; k++) {
System.out.println(words[k]);
}
return words;
}
public static void main(String[] args) throws IOException {
File testFile = new File("try.txt");
getContents(testFile);
}
}
Here is the text file try.txt:
Daisy
Jane
Amanda
Barbara
Alexandra
Ezabile
the output is:
Alexandra
Amanda
Barbara
Ezabile
Jane
Daisy
To solve this problem I have to insert an empty line in the beginning of the text file, is there a way not to do that? I don't know what goes wrong?
I compiled your code (on a Mac) and it works for me. Try opening the file in a hexeditor and see if there is some special character at the beginning of your file. That might be causing the sorting to be incorrect for the first line.
You probably have a BOM (Byte Order Marker) at the beginning at the file. By definition they will be interpreted as zero-width non-breaking-space.
So if you have
String textA = new String(new byte[] { (byte)0xef, (byte)0xbb, (byte) 0xbf, 65}, "UTF-8");
String textB = new String(new byte[] { 66}, "UTF-8");
System.err.println(textA + " < " + textB + " = " + (textA.compareTo(textB) < 0));
The character should show up in your length of the strings, so try printing the length of each line.
System.out.println(words[k] + " " + words[k].length());
And use a list or some other structure so you don't have to read the file twice.
Try something simpler, like this:
public static String[] getContents(File aFile) throws IOException {
List<String> words = new ArrayList<String>();
BufferedReader input = new BufferedReader(new FileReader(aFile));
String line;
while ((line = input.readLine()) != null)
words.add(line);
Collections.sort(words);
return words.toArray(new String[words.size()]);
}
public static void main(String[] args) throws IOException {
File testFile = new File("try.txt");
String[] contents = getContents(testFile);
for (int k = 0; k < contents.length; k++) {
System.out.println(contents[k]);
}
}
Notice that you don't have to iterate over the file to determine how many lines it has, instead I'm adding the lines to an ArrayList, and at the end, converting it to an array.
Use List and the add() method to read your file contents.
Then use Collections.sort() to sort the List.

Categories

Resources