I have to read a dict.txt file which contains one string for line and add these to an arraylist.
I tried this:
public ArrayList<String> myDict = new ArrayList<String>();
InputStream is = (getResources().openRawResource(R.raw.dict));
BufferedReader r = new BufferedReader(new InputStreamReader(is));
try {
while (r.readLine() != null) {
myDict.add(r.readLine());
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
but something wrong...
You are iterating twice in each loop
String line;
while ((line=r.readLine()) != null) {
myDict.add(line);
}
Using Apache IOUtils:
List<String> lines = IOUtils.readLines(inputStream, "UTF-8");
Related
i am trying to create a program that checks a file and prints lines back to me if they contain the word "TRUE"
here is the file contents
TRUE,TRUE
FALSE,TRUE
FALSE,FALSE
TRUE,FALSE
TRUE,TRUE
TRUE,FALSE
here is the program
public static void main(String[] args) {
// TODO Auto-generated method stub
BufferedReader reader;
try {
reader = new BufferedReader(new FileReader(
"C:\\Users\\tree3\\Desktop\\Programming\\file.txt"));
String line = reader.readLine();
while (line != null) {
if(line.contains("TRUE")) {
System.out.println(line);
// read next line
line = reader.readLine();
} else {
System.out.println("false");
}
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
the program just prints false indefinitely
why is this?
public static void main(String[] args) {
try (BufferedReader reader = new BufferedReader(new FileReader("C:\\Users\\tree3\\Desktop\\Programming\\file.txt"))) {
String line = reader.readLine();
while (line != null) {
if (line.contains("TRUE")) {
System.out.println(line);
} else {
System.out.println("false");
}
// read next line
line = reader.readLine();
}
} catch (IOException e) {
e.printStackTrace();
}
}
Do not read next line in side an if statement. What if the if statement is not true? You will never go ahead and be stuck on that line indefinitely.
Use try-with-resources (Java 7+) and don't worry about closing resources.
Cleaner (Java 8+):
try (BufferedReader reader = new BufferedReader(new FileReader("C:\\Users\\tree3\\Desktop\\Programming\\file.txt"))) {
reader.lines().forEach(line -> System.out.println(line.contains("TRUE")));
} catch (IOException e) {
e.printStackTrace();
}
I am trying to read a file but it is asking for two try-catch blocks, one for opening a file and another for reading its content. Why is this required?
String line = null;
try {
File file = new File("F:\\Mobile Extractor.txt");
BufferedReader reader = new BufferedReader(new FileReader(file));
while((line=reader.readLine())!=null) {
System.out.println(line);
}
reader.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Consider using finally block for avoiding memory leaks and closing the streams if you are using versions before 7. From Java 7 on wards you can use try with resources is the best practice
String line = null;
File file = new File("F:\\Mobile Extractor.txt");
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(reader!=null){
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
Try-with-Resources:
String line = null;
File file = new File("F:\\Mobile Extractor.txt");
try(BufferedReader reader = new BufferedReader(new FileReader(file));) {
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
The declaration statement appears within parentheses immediately after the try keyword. The class BufferedReader, in Java SE 7 and later, implements the interface java.lang.AutoCloseable. Because the BufferedReader instance is declared in a try-with-resource statement, it will be closed regardless of whether the try statement completes normally or abruptly (as a result of the method BufferedReader.readLine throwing an IOException).
Try java8, you will not require anything. You can simply do it like this.
import java.nio.file.Files;
import java.nio.file.Paths;
Files.lines(Paths.get(path))
.filter(l -> l.contains(searchWord)).forEach(System.out::println);
The try-catch block is required for IOException.
It will check for the contents available in the file. If there are no contents, then IOException would be thrown else the contents will be displayed.
It should be like:
String line = null;
try {
File file = new File("F:\\Mobile Extractor.txt");
BufferedReader reader = new BufferedReader(new FileReader(file));
try {
while((line=reader.readLine())!=null)
{
System.out.println(line);
}
} catch(IOException ex)
{
System.out.println(ex.getMessage());
}
reader.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
In my app I am displaying the first portion of each line of the CSV in a JList, and when it is selected and a button is pressed (delete) I want it to remove that line from the file based on the first entry. I am trying the method where you have a temp file then write to it then rename it at the end but that isnt working out for some reason. Any ideas?
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
// Delete service
String selected = (String) jList1.getSelectedValue();
File passwords = new File("/users/aak7133/desktop/passwords.txt");
File temp = new File("/users/aak7133/desktop/temp.txt");
try {
BufferedReader reader = new BufferedReader(new FileReader(passwords));
BufferedWriter writer = new BufferedWriter(new FileWriter(temp));
String line;
System.out.println(selected);
while ((line = reader.readLine()) != null) {
// trim newline when comparing with lineToRemove
//String trimmedLine = line.trim();
if (line.contains(selected)) {
continue;
}
writer.write(line);
}
boolean successful = temp.renameTo(passwords);
} catch (Exception e) {
}
updateList();
clearFields();
}
The problem is actually caused by the open reader and writer. This should work:
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
String selected = (String) jList1.getSelectedValue();
BufferedReader reader = null;
BufferedWriter writer = null;
try {
File passwords = new File("/users/aak7133/desktop/passwords.txt");
File temp = File.createTempFile("temp", ".txt", new File("/users/aak7133/desktop/"));
reader = new BufferedReader(new FileReader(passwords));
writer = new BufferedWriter(new FileWriter(temp));
String line;
System.out.println(selected);
while ((line = reader.readLine()) != null) {
// trim newline when comparing with lineToRemove
// String trimmedLine = line.trim();
if (line.contains(selected)) {
continue;
}
writer.write(line + "\n");
}
if (passwords.canWrite()) {
try {
reader.close();
reader = null;
} catch (IOException ignore) {}
try {
writer.close();
writer = null;
} catch (IOException ignore) {}
String path = passwords.getAbsolutePath();
passwords.delete();
boolean successful = temp.renameTo(new File(path));
System.out.println(successful);
}
} catch (Exception e) {
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException ignore) {}
}
if (writer != null) {
try {
writer.close();
} catch (IOException ignore) {}
}
}
updateList();
clearFields();
}
I figured out I needed to put passwords.delete() before temp.renameTo(passwords). This fixed the issue right away.
Forgive me if the question is stupid, but I cannot move the reader to a second line. Calling function on every input line is important.
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("input.txt"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
while ((reader.readLine()) != null) {
///////////
}
Try that:
BufferedReader reader = null;
try {
String line;
reader = new BufferedReader(new FileReader("input.txt"));
while ((line = reader.readLine()) != null) {
myFunc (line);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (reader!=null)
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
You can also use a Scanner instead:
File file = new File ("input.txt");
Scanner scanner = null;
try {
scanner = new Scanner(file);
while (scanner.hasNextLine()) {
myFunc (scanner.nextLine());
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (scanner!=null)
scanner.close();
}
You just need to store the value returned by reader.readLine into an additional variable (just like I said in my comment). Modify your code to look like the following:
String line = null;
while ((line = reader.readLine()) != null) {
//use "line" as per your needs
}
I am finding some difficulties to do the following operation in Java:
I have to take the content of an xml file and print it
I do something like this:
System.out.println("settings.xml: " + ClassLoader.getSystemResourceAsStream("/home/andrea/Documenti/dir1/dir2/dir3/dir4/dir5/dir6/dir7/dir8/src/settings.xml"));
The problem is that the result of this statment is:
settings.xml: null
Why? What can I do to do it?
Tnx
Andrea
You can use this function:
private String getStringFromFile(File file)
{
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try
{
br = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
while ((line = br.readLine()) != null)
{
sb.append(line);
}
} catch (IOException e)
{
e.printStackTrace();
}
finally
{
if (br != null)
{
try
{
br.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
return sb.toString();
}
For example:
System.out.println("settings.xml: " + ClassLoader.getSystemResourceAsStream("home/andrea/Documenti/dir1/dir2/dir3/dir4/dir5/dir6/dir7/dir8/src/settings.xml"));