I am using BufferedReader to read file in java.
Following is the code snippet:
String line;
br = new BufferedReader(new FileReader("file1.txt"));
while ((line = br.readLine()) != null) {
System.out.println(line);
}
//Here I want to open file named "file2.txt".
As mentioned in the code snipped above, i want to now open a new file.
What is the best way to do so ?
Should i first close br using br.close, and then again initialise br or what ?
P.S.: I am new to Java.
Creating a method will make your code modular and easy to use. This will lead to re-usability of code and ease of understanding. Here is the sample code:
public static void main(String args[]) {
readFile("C:\\sample.txt");
}
public static void readFile(String filename) {
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader(filename));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
I would make a method and call it twice
void readFile(String fileName) throws IOException {
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
...
}
}
note that BufferedReader instance br will be closed automatically and make sure that you are using JDK 7 for this
File I/O operations internally use Decorator pattern. So, .close() on the outermost object should close all internal I/Os
Yes, close it first, but use this pattern ...
BufferedReader br = null;
String line;
try {
br = new BufferedReader(new FileReader("file1.txt"));
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
finally {
if (br != null) br.close();
}
//Here I want to open file named "file2.txt".
Or, the try-with-resources approach (semantically equivalent to the above) ...
String line;
try (BufferedReader br = new BufferedReader(new FileReader("file1.txt")) {
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
//Here I want to open file named "file2.txt".
Related
I have a problem and can't find a good solution to it. I need to read a textfile with large amount of data (file has 16MB). The file contains 12 columns with integer values in each one. Generally my problem is how to do this without freezing the app. I have my file in the assets folder of my project and I tried using something like this:
AssetManager assetManager = this.getAssets();
try {
InputStream inputStream = assetManager.open("3333.ecg");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String str;
while ((str = bufferedReader.readLine()) != null) {
stringBuilder.append(str);
}
} catch (IOException e) {
e.printStackTrace();
}
But app freezes. My goal is to get the data from each column and save it into an arraylist of integers. I'm looking for some advice.
Thanks in advance.
Use this to run it in background:
AsyncTask.execute(new Runnable() {
#Override
public void run() {
AssetManager assetManager = this.getAssets();
try {
InputStream inputStream = assetManager.open("3333.ecg");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String str;
while ((str = bufferedReader.readLine()) != null) {
stringBuilder.append(str);
}
} catch (IOException e) {
e.printStackTrace();
}
}
});
I am trying to do same in Eclipse to print a text file and highlight a particular line, but am only able to read text file and not the line in it. Following is my code:
import java.io.*;
public class Bible {
public static void main(String[] args) {
try {
FileReader reader = new FileReader("temp.txt");
int character;
while ((character = reader.read()) != -1) {
System.out.print((char) character);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Correct code to read a file line by line is
public static void main(String[] args) {
BufferedReader br = null;
FileReader fr = null;
try {
//br = new BufferedReader(new FileReader(FILENAME));
fr = new FileReader(FILENAME);
br = new BufferedReader(fr);
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
if (fr != null)
fr.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Now comes the code to highlight.
There are multiple options to do it.
Use html codes in file e.g.
origString = origString.replaceAll(textToHighlight,"<font color='red'>"+textToHighlight+"</font>");
Textview.setText(Html.fromHtml(origString));
Use spannable texts
String text = "Test";
Spannable spanText = Spannable.Factory.getInstance().newSpannable(text);
spanText.setSpan(new BackgroundColorSpan(0xFFFFFF00), 14, 19, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(spanText);
Use some third party library
EmphasisTextView and
Android TextView Link Builder
this is my php code checker code for java application but i want to scan a new file in my java GUI program...
public class test {
public static void main(String[] args) throws MalformedURLException, IOException {
URL u = new URL("http://www.example.com/my/php/doc.php");
URLConnection c = u.openConnection();
InputStream r = c.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(r));
for (String line;
(
line = reader.
`enter code here`
readLine()) != null;
)
System.out.println(line);
This code opens file from the web but I want to open file from the desktop
You can use classes available in the java.io package to read from files. For e.g like this:
public class TextFileReadingExample {
public static void main(String[] args) {
try {
FileReader reader = new FileReader("C:\\Users\\MyUsername\\Desktop\\MyFile.txt");
BufferedReader bufferedReader = new BufferedReader(reader);
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Try to use: new File(your_path).toURI().toURL();
i.e.
public class Main {
public static void main(String[] args) throws MalformedURLException, IOException {
URL u = new File("E:\\test_data_014.lst").toURI().toURL();
URLConnection c = u.openConnection();
InputStream r = c.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(r));
BufferedReader bufferedReader = new BufferedReader(reader);
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
reader.close();
}
}
I'm implementing custom script rule plugin for Sonar.
I want to make a checking rule directly for the source code
and not from checking tokens or nodes of the ASTtree.
Having the follow code:
#Override
public void visitFile() {
BufferedReader br = null;
File file = null;
String line = null;
try {
file = this.getSourceCode().getFile();
br = new BufferedReader(new FileReader(file));
while ((line = br.readLine()) != null) {
...
}
}
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
My problem is that the :
this.getSourceCode().getFile();
returns back null
how can I get the instance of the file for which was actually the visitFile() called?
How does 'visitFile()' works actually?
I tried to read an ANSI encoded Arabic file in Java using the following two way
Scanner scanner = null;
try {
scanner = new Scanner(new File("test/input.txt"), "ISO-8859-6");
while (scanner.hasNextLine()) {
String input =scanner.nextLine();
processString(input);
}
I tried also to read with default encoding (i.e. I omitted the "ISO-8859-6")
Any suggestions?
Try this code:
public static void transform(File source, String srcEncoding, File target, String tgtEncoding) throws IOException {
BufferedReader br = null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream(source), Charset.forName(srcEncoding)));
bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(target), tgtEncoding));
char[] buffer = new char[16384];
int read;
while ((read = br.read(buffer)) != -1) {
bw.write(buffer, 0, read);
}
} finally {
try {
if (br != null) {
br.close();
}
} finally {
if (bw != null) {
bw.close();
}`enter code here`
}
}
}
Look at this:
private static final String FILENAME = "/Users/jucepho/Desktop/ansi.txt";
public static void main(String[] args) {
BufferedReader br = null;
FileReader fr = null;
try {
fr = new FileReader(FILENAME);
br = new BufferedReader(fr);
String sCurrentLine;
br = new BufferedReader(new FileReader(FILENAME));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
br.close();
if (fr != null)
fr.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
This file has this characters http://www.alanwood.net/demos/ansi.html