When to use String and when char array in Java? - java

I am supposed to read a large file containing a string in each line. What is the best way to parse this kind of file in Java?
Currently I am parsing like this using BufferedReader:
public static List<String> readFile(String filename) {
List<String> input = new ArrayList<>();
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader(filename));
while ((sCurrentLine = br.readLine()) != null) {
input.add(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null) br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
return input;
}
So my question here is, which one is a better way: to save like an array of String or an array of char arrays?
In other words, is it better to have too many String objects or too many char arrays?
EDIT:
I need to check if the string in each line is a palindrome or not.

In above scenario, you can use either of these. If you want change the content further, then you have to use array of char because String is immutable in nature in java.

Related

Read file, one line at a time and run code

I have a file with text in this format:
text:text2:text3
text4:text5:text6
text7:text8:text9
Now what I want to do, is to read the first line, separate the words at the ":", and save the 3 strings into different variables. those variables are then used as parameter for a method, before having the program read the next line and doing the same thing over and over again.. So far I've got this:
public static void main(String[] args) {
BufferedReader reader = null;
try {
File file = new File("C://Users//Patrick//Desktop//textfile.txt");
reader = new BufferedReader(new FileReader(file));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Also, I've tried this for separation (although not sure Array is the best option:
String[] strArr = sCurrentLine.split("\\:");
Use String[] parts = line.split(":"); to get an array with text, text2 etc. You can then loop through parts and call the method you want with each item in the list.
Your original split does not work, because : is not a special character in Regex. You only have to use an escape character when the split you are trying to achieve uses a special character.
More information here.

Reading a text file (~90,000 words) and trying to add each word into an ArrayList of strings

My method read and prints the file, but I am having trouble adding each word to the ArrayList dict.
The reader reads the file one char at a time, so what I have written adds each char to dict: [c,a,t,d,o,g] when I want [cat,dog]. The text file has the words on their own line; how can I distinguish them?
My code so far:
public static List Dictionary() {
ArrayList <String> dict = new ArrayList <String>();
File inFile = new File("C:/Users/Aidan/Desktop/fua.txt");
FileReader ins = null;
try {
ins = new FileReader(inFile);
int ch;
while ((ch = ins.read()) != -1) {
System.out.print((char) ch);
dict.add((char) ch + "");
}
} catch (Exception e) {
System.out.println(e);
} finally {
try {
ins.close();
} catch (Exception e) {
}
}
return dict;
}
Please observe Java naming conventions, so readDictionary instead of Dictionary (which looks like a class name). Next, I would pass the fileName into the method (instead of hard-coding the path in your method). Instead of reinventing the wheel, I would use a Scanner. You can also use the try-with-resources instead of finally here (and the diamond operator). Like,
public static List<String> readDictionary(String fileName) {
List<String> dict = new ArrayList<>();
try (Scanner scan = new Scanner(new File(fileName))) {
while (scan.hasNext()) {
dict.add(scan.next());
}
} catch (Exception e) {
System.out.printf("Caught Exception: %s%n", e.getMessage());
e.printStackTrace();
}
return dict;
}
Alternatively, use a BufferedReader and split each word yourself. Like,
public static List<String> readDictionary(String fileName) {
List<String> dict = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader(
new File(fileName)))) {
String line;
while ((line = br.readLine()) != null) {
if (!line.isEmpty()) {
Stream.of(line.split("\\s+"))
.forEachOrdered(word -> dict.add(word));
}
}
} catch (Exception e) {
System.out.printf("Caught Exception: %s%n", e.getMessage());
e.printStackTrace();
}
return dict;
}
But that is basically what the first example does.
Check out the answer here which shows how to use Scanner to get words from a file: Read next word in java.
Instead of printing out the words, you'd want to append them to an ArrayList.
As the read method of the FileReader can only read a single character at a time and that's not what you want, then I would suggest you use a Scanner to read the file.
ArrayList<String> dict = new ArrayList<>();
Scanner scanner = new Scanner(new File("C:/Users/Aidan/Desktop/fua.txt"));
while(scanner.hasNext()){
dict.add(scanner.next());
}
You can wrap your FileReader in a BufferedReader, which has a readLine() method that will get you an entire line (word) at a time. readLine() returns null when there are no more lines to read.

Format a String in Json style

I extracted a huge String from a webpage and want to style/formatting this in Json style. The extracted String was originally a Json format but now after extracting this is just a long String. I used JsonObj for this and the formatter does curios things, he moved text from the bottom to top changed the generally the line orders etc.
http://pastebin.com/exwwc6SY JsonFile after Formatting
http://pastebin.com/WHXtE36G The extracted String
And here the code
try {
FileWriter fw = new FileWriter("/tmp/1.txt");
String line = ROUtils.getStringFromInputStream(urlConnection.getInputStream());
System.out.println(line);
String jsonObj = new JSONObject(line).toString(2);
fw.write(jsonObj);
} catch (IOException e) {
e.printStackTrace();
}
And the getStringFromInputStream() method
public static String getStringFromInputStream(InputStream is) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (br != null) {
try {
br.close();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
return sb.toString();
}
Update
I found a new issue. The JsonObj File its not equal to the original String.
I compared the number of Characters (no spaces). The original String has 96311 and the JsonObj has 92636. Can anyone give me a hint what should I do?
You cannot and should not rely on the ordering of elements within a JSON object.
From the JSON specification at http://www.json.org/
An object is an unordered set of name/value pairs.
I found it out why i missed 4000 characters after converting.
I forgot to close the FileWriter!
fw.close();
The close() methods calls the flush() method so that the last buffered piece of the String can written down.
Thank u guys.

Reading from a text file in java is returning some garbage value

I'm performing certain commands through command prompt and storing the values in a text file.
wmic logicaldisk where drivetype=3 get deviceid > drive.txt
Now I want to read the string stored in the text file from my java file. When I try to do this:
try {
File file = new File("drive.txt");
FileReader reader = new FileReader(file);
BufferedReader in = new BufferedReader(reader);
int i=0;
while ((string[i] = in.readLine()) != null) {
System.out.println(string[i]);
++i;
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
I get the output as follows:
ÿþD[]E[]V[]I[]C[]E[]
how to avoid this?
while ((string[i] = in.readLine()) != null) {
System.out.println(string[2]);
}
over there you are missing the i++;
However I would advise you to use this structure: Use a ArrayList instead of an array, since this allows you to have a self-resizing structure, also instead in the while use the method ready(); from the BufferedRead in order to check the end from the document, at the end the for it's just to display the elements in String ArrayList.
ArrayList<String> string = new ArrayList<String>();
try {
File file = new File("drive.txt");
BufferedReader entrada;
entrada = new BufferedReader(new FileReader(file));
entrada.readLine();
while (entrada.ready()) {
string.add(entrada.readLine());
}
entrada.close();
} catch (IOException e) {
e.printStackTrace();
}
for (String elements : string) {
System.out.println(elements);
}
Why do you need a string array here? The size of the array may be wrong? Simply use a string instead of array. I tried this and works fine for me:
try {
String string;
File file = new File("drive.txt");
FileReader reader = new FileReader(file);
BufferedReader in = new BufferedReader(reader);
int i = 0;
while ((string = in.readLine()) != null) {
System.out.println(string);
++i;
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
If you are using eclipse IDE, change the encoding type. Go to Edit->Set Encoding-> Others->UTF-8.

How to get the content of an input stream in reverse order?

I am using a txt file for my level desing. I use the below to take the contents and convert to string buffer, then iterate through the lines to generate my game objects.
The the problem is that it reads from top down and so I have to design my levels upside down for them to be right way around.
How can I change the stream to read the opposite way? Or write the lines to the String Builder the opposite way?
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append((line + "\n"));
}
} catch (IOException e) {
Log.w("LOG", e.getMessage());
} finally {
try {
is.close();
} catch (IOException e) {
Log.w("LOG", e.getMessage());
}
}
return sb.toString();
You could just use sb.insert(0, line + "\n") instead of sb.append(line + "\n");.
This will always add new lines to the front of the string, not append it to the end. Should do exactly what you want and will be just as fast, because StringBuilder is made exactly for things like that.

Categories