I'm reading a txt with BuffererReader and I wonder how to give the path to my txt in BufferedReader's argument.
BufferedReader input = new Bufferedreader(
new FileReader(D:VI.félév\Prog gyak\Project\proba.txt));
This doesn't seem to work.
Your problem is:
new Filereader( .. )
should be
new FileReader( .. )
And the path has to look like:
new FileReader("D:\\directory\\proba.txt");
You need an additional \ as escape character
Full Working Example with try..catch if problem any occur.
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("D:\\directory\\proba.txt"));
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();
}
}
Related
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";
What i'm trying to do, is to replace a symbol in a file text which contains over 4000 lines but using the below code, after the program ends, it only remain 500 lines. Why is this file truncated? How to solve this?
This is my code:
ArrayList<String> arrayList = new ArrayList<>();
try (FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader)) {
String line;
while ((line = bufferedReader.readLine()) != null) {
line = line.replace("þ", "t");
arrayList.add(line);
try (BufferedWriter bw = new BufferedWriter(new FileWriter(file))) {
for (String string : arrayList) {
bw.write(string + "\n");
}
} catch (Exception e) {System.err.println(e);}
}
} catch (Exception e) {e.printStackTrace();}
Thanks in advance!
new BufferedWriter(new FileWriter(file)) clear file.
You should open it only once. Also you reading and writing to the same file. You should use different files.
Like this
try (FileReader fileReader = new FileReader(inputFile);
BufferedReader bufferedReader = new BufferedReader(fileReader);
BufferedWriter bw = new BufferedWriter(new FileWriter(outputFile))) {
String line;
while ((line = bufferedReader.readLine()) != null) {
line = line.replace("þ", "t");
bw.write(line + "\n");
}
} catch (Exception e) {
e.printStackTrace();
}
You are writing to the same file while you are reading it. This won't work. Once you start writing, the file becomes empty (plus whatever you've written), so subsequent reads will report end-of-file. Your ~500 lines will be buffered input from the first read.
One solution is to do all the reading first, before opening the file again for writing:
Array<String> arrayList = new ArrayList<>();
try (BufferedReader bufferedReader = new BufferedReader(new FileReader(file))) {
while ((String line = bufferedReader.readLine()) != null) {
line = line.replace("þ", "t");
arrayList.add(line);
}
} catch (Exception e) {
e.printStackTrace();
}
try (BufferedWriter bw = new BufferedWriter(new FileWriter(file))) {
for (String string : arrayList) {
bw.write(string + "\n");
}
} catch (Exception e) {
System.err.println(e);
}
Here, first the program slurps the file into a List<String>, fixing the lines as it goes. Then it writes all the lines back out to the file.
There are circumstances in which this model is appropriate. For example, you might be building a non-linear data structure from the file content. Or you might need to see the last line before you can modify earlier lines (and be unable to re-open the data source from the start).
However I'd suggest a method that's more thrifty with memory. You don't need to keep all those lines in memory. You can read one line, fix it up, then forget about it. But to do this, you'll need to write to a second file.
String filein = "inputfile";
String fileout = filein + ".tmp";
try(
BufferedReader reader = new BufferedReader(new FileReader(filein));
Writer writer = new BufferedWriter(FileWriter(fileout))
) {
while ((String line = bufferedReader.readLine()) != null) {
writer.write(line.replace("þ", "t");
}
}
Files.move(Paths.get(fileout)),
Paths.get(filein),
CopyOption.REPLACE_EXISTING);
I have left out the necessary exception catching -- add back in as required.
Isn't there a cleaner way of doing the following (eliminating the need for initializing line prior to the while block)? It just seems unnecessary to intialize a variable prior to its usage instead of doing something like while ((String line = br.readLine) != null) {}. If not, why not?
BufferedReader reader = null;
try
{
File file = new File("sample-file.dat");
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();
}
}
No, you cannot avoid initializing the variable. However, you can use Try-With-Resources to make it a lot cleaner.
try (BufferedReader reader = new BufferedReader(new FileReader("sample-file.dat"))) {
String line;
while ((line = reader.readLine()) != null)
{
System.out.println(line);
}
}
catch (IOException e)
{
e.printStackTrace();
}
Just adding this for completions sake, if anyone is using Java 8, you have access to the Stream API. Using this you can just simply do the following:
BufferedReader reader = new BufferedReader(...);
reader.lines().forEach(System.out::println);
And if you're wondering, the code under the hood that produces this does check for null lines.
No you can't declare (and use) a variable in the while loop expression evaluation step. But, you can eliminate the finally block by using a try-with-resources
try (
File file = new File("sample-file.dat");
BufferedReader reader = new BufferedReader(new FileReader(file));
) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
No, you can't declare a variable inside the condition definition except in a for loop. Can't really say why - perhaps because the condition is not supposed to be somewhere you initialize things, whereas a for initialization step is.
But anyway, especially in cases where the loop conditions are complicated, some coders prefer to use
while (true) {
String line = reader.readLine();
if ( line == null )
break;
System.out.println(line);
}
But it's really a matter of style.
I have an app, that needs to read files line by line. I'm using the following code and it's ok.
public ArrayList <String[]> LoadServersFile(String filename){
BufferedReader br=null;
ArrayList <String> result = new ArrayList();
try {
String sCurrentLine;
InputStreamReader reader = new InputStreamReader(this.getClass().getResourceAsStream("/"+filename));
br = new BufferedReader(new FileReader(filename));
while ((sCurrentLine = br.readLine()) != null) {
result.add(sCurrentLine);
}
br.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(FilesIO.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(FilesIO.class.getName()).log(Level.SEVERE, null, ex);
}
return result;
}
But after compiling project and launching it, br.readLine() is always null. Setting "/file.txt" and putting this file to C:/ disk fixes the bug, but i need this file to be in folder with my .jar file
You can get your file using the getResourceAsStream method:
InputStreamReader reader = new InputStreamReader(this.getClass().getResourceAsStream("/file.txt"));
BufferedReader br = new BufferedReader(reader);
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.