I've been looking around on the Internet trying to figure out which could be the best way to read from text files which are not very long (the use case here involves small OpenGL shaders). I ended up with this:
private static String load(final String path)
{
String text = null;
try
{
final FileReader fileReader = new FileReader(path);
fileReader.read(CharBuffer.wrap(text));
// ...
}
catch(IOException e)
{
e.printStackTrace();
}
return text;
}
In which cases could this chunk of code result in inefficiencies? Is that CharBuffer.wrap(text) a good thing?
If you want to read the file line by line:
BufferedReader br = new BufferedReader(new FileReader(path));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
String everything = sb.toString();
} finally {
br.close();
}
If you want to read the complete file in one go:
String text=new String(Files.readAllBytes(...)) or Files.readAllLines(...)
I would usually just roll like this. The CharBuffer.wrap(text) thing seems to only get you a single character ... File Reader docs
BufferedReader br = new BufferedReader(fr);
StringBuilder sb = new StringBuilder();
String s;
while((s = br.readLine()) != null) {
sb.append(s);
}
fr.close();
return sb.toString();
Related
I tried concatenating 2 lines of text in a given text file and printing the output to the console. My code is very complicated, is there a simpler method to achieve this by using FileHandling basic concepts ?
import java.io.*;
public class ConcatText{
public static void main(String[] args){
BufferedReader br = null;
try{
String currentLine;
br = new BufferedReader(new FileReader("C:\\Users\\123\\Documents\\CS105\\FileHandling\\concat.file.text"));
StringBuffer text1 = new StringBuffer (br.readLine());
StringBuffer text2 = new StringBuffer(br.readLine());
text1.append(text2);
String str = text1.toString();
str = str.trim();
String array[] = str.split(" ");
StringBuffer result = new StringBuffer();
for(int i=0; i<array.length; i++) {
result.append(array[i]);
}
System.out.println(result);
}
catch(IOException e){
e.printStackTrace();
}finally{
try{
if(br != null){
br.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
}
}
The text file is as follows :
GTAGCTAGCTAGC
AGCCACGTA
the output should be as follows (concatenation of the text file Strings) :
GTAGCTAGCTAGCAGCCACGTA
If you are using java 8 or newer, the simplest way would be:
List<String> lines = Files.readAllLines(Paths.get(filePath));
String result = String.join("", lines);
If you are using java 7, at least you can use try with resources to reduce the clutter in the code, like this:
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
StringBuffer text1 = new StringBuffer (br.readLine());
StringBuffer text2 = new StringBuffer(br.readLine());
// ...
}catch(IOException e){
e.printStackTrace();
}
This way, resources will be autoclosed and you don't need to call br.close().
Short answer, there is:
public static void main(String[] args) {
//this is called try-with-resources, it handles closing the resources for you
try (BufferedReader reader = new BufferedReader(...)) {
StringBuilder stringBuilder = new StringBuilder();
String line = reader.readLine();
//readLine() will return null when there are no more lines
while (line != null) {
//replace any spaces with empty string
//first argument is regex matching any empty spaces, second is replacement
line = line.replaceAll("\\s+", "");
//append the current line
stringBuilder.append(line);
//read the next line, will be null when there are no more
line = reader.readLine();
}
System.out.println(stringBuilder);
} catch (IOException exc) {
exc.printStackTrace();
}
}
First of all read on try with resources, when you are using it you don't need to close manually resources(files, streams, etc.), it will do it for you. This for example.
You don't need to wrap read lines in StringBuffer, you don't get anything out of it in this case.
Also read about the methods provided by String class starting with the java doc - documentation.
I am getting data from php file in android java class using
BufferedReader reader = new BufferedReader(new
InputStreamReader(con.getInputStream()));.
This code is in my php file is
echo "abc";
echo "xyz";
This is the code of my java file.
BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String line = null;
Complete_line = null;// Read Server Response
while ((line = reader.readLine()) != null) {
System.out.println(line);
break;
}
But when I read from Buffer reader it will read a whole one line, or it will print "line" string as "abcxyz". But I want them as two lines as they are two different lines in the PHP file.
try this,
BufferedReader reader = null;
StringBuffer response = new StringBuffer();
try {
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = reader.readLine()) != null) {
response.append(line+"\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
In PHP, unless you seperate the 2 lines a a newline character \n, the two echos are the same. To seperate echos into different lines, you need to end the strings with \n, like this:
echo "abc\n";
echo "xyz\n";
I'm trying to make a program that reads a file name through a text field and displays it in a text area. I will also need a clear button. This is what I have so far:
private void enterButtonActionPerformed(java.awt.event.ActionEvent evt) {
String fileName = jTextField1.getText();
try {
FileReader fr = new FileReader(fileName);
BufferedReader br = new BufferedReader(fr);
String s;
while ((s = br.readLine()) != null) {
jTextArea1.setText(s + "\n");
}
br.close();
} catch (IOException e) {
jTextArea1.setText("File not found!");
}
}
private void clearButtonActionPerformed(java.awt.event.ActionEvent evt) {
jTextField1.setText("");
jTextArea1.setText("");
}
For some reason, it is not reading my text file on my desktop, called "hi". How could I make my program work? What am I doing wrong?
setText does that, sets the text of the field
Now, JTextArea has a simple read method for reading content, for example
try (BufferedReader reader = new BufferedReader(new FileReader(new File("resources/New Text Document.txt")))) {
textArea.read(reader, "File");
} catch (IOException exp) {
exp.printStackTrace();
}
I'm not sure about your problem but this seems not right to me and I want to mention to you to fix it:
Actually what you do is putting the last line of text in your textArea1 and if your last line is "\n" or an empty line, then obviously you don't see anything on your screen.
It would be good to use StringBuffer to store your lines which are read from the file and display the whole text. The following code can help you:
StringBuffer buffer = new StringBuffer();
String s;
while ((s = br.readLine()) != null) {
buffer.append(s).append('\n');
}
jTextArea1.setText(buffer.toString());
your code is actually working and it is reading the file, but your code goes wrong inside the while loop when you are assigning the value you are not concating string inside the while loop i have made some changes to your code try this one.
String fileName = "src/hi.txt";
String content = "";
try {
FileReader fr = new FileReader(fileName);
BufferedReader br = new BufferedReader(fr);
String s;
while ((s = br.readLine()) != null) {
content+="\n"+s;
}
System.out.println(content);
br.close();
} catch (Exception e) {
System.out.println("file not found");
}
public class AddSingleInstance {
public void addinstances(String txtpath,String arffpath) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader("C:\\src\\text.txt"));
FileWriter fw = new FileWriter("C:\\src\\" + test.txt,true);
StringBuilder sb = new StringBuilder();
//String toWrite = "";
String line = null;
while ((line = reader.readLine())!= null){
// toWrite += line;
sb.append(line);
sb.append("\n");
}
reader.close();
fw.write(sb.toString());
fw.flush();
fw.close();
}
}
my code is working on append lines from text file(A) to specific lines in another file(B), like
I
AM
......
(above lines are fixed, cannot be overwriting)
student(New string was added from text file)
now(New string...)
How can I overwrite those lines into file(B) instead of appending them on B?
You can use java.io.RandomAccessFile to access file(B) and write to it at the desired location.
Suppose a file contains the following lines:
#Do
#not
#use
#these
#lines.
Use
these.
My aim is to read only those lines which does not start with #. How this can be optimally done in Java?
Let's assume that you want to accumulate the lines (of course you can do everything with each line).
String filePath = "somePath\\lines.txt";
// Lines accumulator.
ArrayList<String> filteredLines = new ArrayList<String>();
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new FileReader(filePath));
String line;
while ((line = bufferedReader.readLine()) != null) {
// Line filtering. Please note that empty lines
// will match this criteria!
if (!line.startsWith("#")) {
filteredLines.add(line);
}
}
}
finally {
if (bufferedReader != null)
bufferedReader.close();
}
Using Java 7 try-with-resources statement:
String filePath = "somePath\\lines.txt";
ArrayList<String> filteredLines = new ArrayList<String>();
try (Reader reader = new FileReader(filePath);
BufferedReader bufferedReader = new BufferedReader(reader)) {
String line;
while ((line = bufferedReader.readLine()) != null) {
if (!line.startsWith("#"))
filteredLines.add(line);
}
}
Use the String.startsWith() method. in your case you would use
if(!myString.startsWith("#"))
{
//some code here
}
BufferedReader.readLine() return a String. you could check if that line starts with # using string.startsWith()
FileReader reader = new FileReader("file1.txt");
BufferedReader br = new BufferedReader(reader);
String line="";
while((line=br.readLine())!=null){
if(!line.startsWith("#")){
System.out.println(line);
}
}
}