J
js_dev
Reading from files
How do I read from a file in Java?
(File input in Java)
(a)
import java.io.FileReader;//import needed
public class Foo{
String s; int c;
public void somefunc(){
.....
FileReader fr = new FileReader("c:\\temp\\debug.txt");
s = new String();
while ( (c=fr.read()) != -1){
s = s + (char)c;
}
//now s contains the file as a string
.....
}
.....
}
or, still better, make it a function for use at any time:
public String readfile(String fullpath){
try{
FileReader fr = new FileReader(fullpath);
s = new String();
while ( (c=fr.read()) != -1){
s = s + (char)c;
}
}catch(Exception e){
System.out.println("Myfile.java|readfile|Exception, text:" + e);
}
return s;
}
(b)
import java.io.FileInputStream;//import needed
public class Foo{
String s; int c;
public void somefunc(){
.....
FileInputStream fis = new FileInputStream("c:\\temp\\debug.txt");
s = new String();
while ( (c=fis.read()) != -1){
s = s + (char)c;
}
//now s contains the file as a string
.....
}
.....
}
(c)
import java.io.RandomAccessFile;//import needed
public class Foo{
.....
public String readfile(String fullpath){
try{
String s = new String();
String temp = new String();
RandomAccessFile raf = new RandomAccessFile(fullpath,"r");
do {
temp = raf.readLine();
if( temp==null ) {
break;
} else {
s = s + temp;
}
} while(true);
raf.close();
}catch (Exception e) {
System.out.println("Myfile.java|readfile|Exception, text:" + e)
}
return s;
}
How do I read from a file in Java?
(File input in Java)
(a)
import java.io.FileReader;//import needed
public class Foo{
String s; int c;
public void somefunc(){
.....
FileReader fr = new FileReader("c:\\temp\\debug.txt");
s = new String();
while ( (c=fr.read()) != -1){
s = s + (char)c;
}
//now s contains the file as a string
.....
}
.....
}
or, still better, make it a function for use at any time:
public String readfile(String fullpath){
try{
FileReader fr = new FileReader(fullpath);
s = new String();
while ( (c=fr.read()) != -1){
s = s + (char)c;
}
}catch(Exception e){
System.out.println("Myfile.java|readfile|Exception, text:" + e);
}
return s;
}
(b)
import java.io.FileInputStream;//import needed
public class Foo{
String s; int c;
public void somefunc(){
.....
FileInputStream fis = new FileInputStream("c:\\temp\\debug.txt");
s = new String();
while ( (c=fis.read()) != -1){
s = s + (char)c;
}
//now s contains the file as a string
.....
}
.....
}
(c)
import java.io.RandomAccessFile;//import needed
public class Foo{
.....
public String readfile(String fullpath){
try{
String s = new String();
String temp = new String();
RandomAccessFile raf = new RandomAccessFile(fullpath,"r");
do {
temp = raf.readLine();
if( temp==null ) {
break;
} else {
s = s + temp;
}
} while(true);
raf.close();
}catch (Exception e) {
System.out.println("Myfile.java|readfile|Exception, text:" + e)
}
return s;
}