Read text file at one step [duplicate] - java

This question already has answers here:
What is simplest way to read a file into String? [duplicate]
(9 answers)
Java 1.4.2 - Reading Files
(3 answers)
Closed 7 years ago.
I need to read text file to String. I do :
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(filePath));
String line = br.readLine();
String everything = line;
while (line != null) {
line = br.readLine();
everything += line + "\n";
}
} catch (IOException e) {
e.printStackTrace();
}
finally {
try {
if (br != null)
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
But I dont like to read line by line. It should be possible to read whole file to string at one function call. I'm right? By the way, I must use java 1.4.

you can read the whole file data as byte array.
File file = new File(yourFileName);
FileInputStream fis = new FileInputStream(file);
byte[] data = new byte[(int) file.length()];
fis.read(data);
fis.close();
String strData=new String(data, "UTF-8"); // converting byte array to string
System.out.println(strData);

If you are allowed to use an external library, you could have a look on Apache Commons FileUtils
Besides, you definitely should not use such an old java version.

Related

Android Read a Text file Exactly

I have a text file that has been signed and I need to read this file into a string exactly as it is. The code I am currently using:
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
invitationText.append(line);
invitationText.append('\n');
}
invitationText.deleteCharAt(invitationText.length()-1);
Works if the file has no return at the end, but if it did have a return then the signature check would fail. There's a lot of questions around this so I'm having a hard time finding one that specifically answer this, so this may be a duplicate question. Some restrictions I have though are:
It can't use the methods added in Java 7 (I'm on android, I don't have access)
It can't use the org.apache IOUtils method (I can't bring in that library)
Whether it loops or reads the whole thing in one go doesn't matter to me I just need 100% guarantee that regardless of carriage returns in the file, the file will get read in exactly as it is on disk.
Here's what I use:
public static String readResponseFromFile() throws IOException {
File path = "some_path";
File file = new File(path, "/" + "some.file");
path.mkdirs();
String response = null;
if (file != null) {
InputStream os = new FileInputStream(file);
try {
byte[] bytes = new byte[(int) file.length()];
os.read(bytes);
response = new String(bytes);
os.close();
} catch (IOException ioEx) {
throw ioEx;
} finally {
if (os != null) {
os.close();
}
}
}
return response;
}

Reading a txt file (weird symbols) JAVA

im trying to read a txt file downloaded from an arduino server. I can download the file and save it on internal storage, but when i want to read it, i see weird symbols and i can't see all saved text, only 6 o 7 characters. I don't know what happen.
public void downloadFile (String fileDownloadPath, String saveFilePath){
try{
File SaveFile = new File(saveFilePath);
URL u= new URL ("http://169.254.0.1:44300/169.254.0.1");
URLConnection con=u.openConnection();
int lengthofContent=con.getContentLength();
DataInputStream DIStream = new DataInputStream(u.openStream());
byte [] buffer = new byte[2000];
DIStream.read(buffer);
DIStream.close();
DataOutputStream DOStream = new DataOutputStream(new FileOutputStream(SaveFile));
DOStream.write(buffer);
DOStream.flush();
DOStream.close();
System.out.println ("o");
hideProgressIndicator();
} catch (FileNotFoundException e){
hideProgressIndicator();
}
catch (IOException e){
hideProgressIndicator();
}
catch (Exception e){
}
}
when i want to read it i use this:
private String readFile() {
String result = "", line;
try
{
BufferedReader br = new BufferedReader((new FileReader("/data/data/com.example.sensolog/files/LOL.txt")));
while((line = br.readLine()) != null)
{
result += line + "\n";
}
System.out.println (result);
br.close();
}
catch(Exception e)
{
e.printStackTrace();
}
return result ;
}
And the results are the followings :
08-26 15:38:11.498: I/System.out(30593): SERVIDORn�����������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������...
Define the encoding of the file while reading, here is an example:
BufferedReader br = new BufferedReader(( new FileReader("/data/data/com.example.sensolog/files/LOL.txt"),"ISO-8859-1"));
You're downloading and storing the file as a DataOutputStream - Which can only be read again by a DataInputStream - Is that your intention? I would save the file as a simple text file, unless you absolutely must save as a binary type?
Further information on DataOutputStream:
Wraps an existing OutputStream and writes big-endian typed data to it. Typically, this stream can be read in by DataInputStream. Types that can be written include byte, 16-bit short, 32-bit int, 32-bit float, 64-bit long, 64-bit double, byte strings, and MUTF-8 encoded strings. from: http://developer.android.com/reference/java/io/DataOutputStream.html

Read a .txt file of SD in Android [duplicate]

This question already has answers here:
android reading from a text file
(3 answers)
How to load text from file to textview [duplicate]
(3 answers)
Closed 9 years ago.
My problem with the software I'm trying to make is this;
when I save the information, it's saved with this code:
With this, the information is saved in a text in the SD,
but I couldn't to read that information. I've tried with several ways.
I want to save the content of the TXT in a String to put it in a TextView.
try
{
String myData ;
FileInputStream fis = new FileInputStream(your file name);
DataInputStream in = new DataInputStream(fis);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
myData = myData + strLine;
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
// play with myData..It's file content
I have tried this code and it works perfectly :D
File ruta_sd = Environment.getExternalStorageDirectory();
File f = new File(ruta_sd.getAbsolutePath(), "datos.txt");
BufferedReader fin =new BufferedReader(
new InputStreamReader(
new FileInputStream(f)));
String texto = fin.readLine();
fin.close();
textohere.setText(texto);

How to read or replace multiple lines of a file all at once? [duplicate]

This question already has answers here:
How to read a file into string in java?
(14 answers)
Closed 9 years ago.
I am currently writing an encryption program that encrypts text documents with 64Bit encryption. The way it works is that it takes a string, and encrypts the string. I am currently searching for a way to have the program store all contents of a file in a string, encrypt the string, and then overwrite the file with the encrypted string. However, using
while((bufferedReader.readLine()) != null) {
...
}
it only reads and encrypts the first line, and the rest of it remains untouched.
however, using:
List<String> lines = Files.readAllLines(Paths.get(selectedFile.toString()),
Charset.defaultCharset());
for (String line : lines) {
...
}
only the last line is encrypted. I honestly don't know what to do anymore, as I am kind of running out of ideas.
Here is my current code (which also only appends to the file, as I was trying something new.) :
public static void Encrypt() throws Exception {
try {
FileWriter fw = new FileWriter(selectedFile.getAbsoluteFile(), true);
BufferedWriter bw = new BufferedWriter(fw);
List<String> lines = Files.readAllLines(Paths.get(selectedFile.toString()),
Charset.defaultCharset());
for (String line : lines) {
System.out.println(line);
System.out.println(AESencrp.encrypt(line));
bw.write(AESencrp.encrypt(line));
}
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
BufferedReader#readLine will return the line of text read from the reader. In you're example, you are ignoring the return value.
Instead, you should be doing something like...
String text = null;
while((text = bufferedReader.readLine()) != null) {
// Process the text variable
}
I dont think that encrypting line by line is a good idea. I would do it this way
Cipher cipher = ...
Path path = Paths.get(file);
File tmp = File.createTempFile("tmp", "");
try (CipherOutputStream cout = new CipherOutputStream(new FileOutputStream(tmp), cipher)) {
Files.copy(path, cout);
}
Files.move(tmp.toPath(), path, StandardCopyOption.REPLACE_EXISTING);
and read encrypted text like this
Scanner sc = new Scanner(new CipherInputStream(new FileInputStream(file), cipher));
while(sc.hasNextLine()) {
...
Try the next:
public static void Encrypt() throws Exception {
try {
Path path = Paths.get(selectedFile.toURI());
Charset charset = Charset.defaultCharset();
// Read file
List<String> lines = Files.readAllLines(path, charset);
// Encrypt line
lines.set(0, AESencrp.encrypt(lines.get(0)));
// Write file
Files.write(path, lines, charset);
} catch (IOException e) {
e.printStackTrace();
}
}

Return the text of a file as a string? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How to create a Java String from the contents of a file
Is it possible to process a multi-lined text file and return its contents as a string?
If this is possible, please show me how.
If you need more information, I'm playing around with I/O. I want to open a text file, process its contents, return that as a String and set the contents of a textarea to that string.
Kind of like a text editor.
Use apache-commons FileUtils's readFileToString
Check the java tutorial here -
http://download.oracle.com/javase/tutorial/essential/io/file.html
Path file = ...;
InputStream in = null;
StringBuffer cBuf = new StringBuffer();
try {
in = file.newInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
cBuf.append("\n");
cBuf.append(line);
}
} catch (IOException x) {
System.err.println(x);
} finally {
if (in != null) in.close();
}
// cBuf.toString() will contain the entire file contents
return cBuf.toString();
Something along the lines of
String result = "";
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
dis = new DataInputStream(bis);
while (dis.available() != 0) {
// Here's where you get the lines from your file
result += dis.readLine() + "\n";
}
fis.close();
bis.close();
dis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
String data = "";
try {
BufferedReader in = new BufferedReader(new FileReader(new File("some_file.txt")));
StringBuilder string = new StringBuilder();
for (String line = ""; line = in.readLine(); line != null)
string.append(line).append("\n");
in.close();
data = line.toString();
}
catch (IOException ioe) {
System.err.println("Oops: " + ioe.getMessage());
}
Just remember to import java.io.* first.
This will replace all newlines in the file with \n, because I don't think there is any way to get the separator used in the file.

Categories

Resources