Method read from file using java language - java

I will enhance an old algorithm which use java language and i want it to read the text from file to encrypt it SO I will make a method that reads the text line by line from file then store them in array. I made this method and it works BUT the variable "line2" reads the first line correctly but once the next line come it will erase the first line and put the second line so what can i do please??
// The CODES
Private byte[] line2;
public byte[] readFromFile (){
try (BufferedReader br = new BufferedReader(new FileReader ("C:\\Users\\just\\Desktop\\message.txt")))
{
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
line2 = sCurrentLine.getBytes();
}
} catch (IOException e) {
e.printStackTrace();
}
return line2;
}

I do it like this :
public byte[] readFromFile ()throws IOException
{
BufferedReader br = new BufferedReader(new FileReader("C:\Users\just\Desktop\message.txt"));
int k = 0;
int f=0;
byte[] line2;
// -1 means END, I made this loop to count the length of the file
while (br.read() != -1)
{ f++;
}
byte[] array2 = new byte[f];
String sCurrentLine;
while ((sCurrentLine = br.readLine()) != null) {
line2 = sCurrentLine.getBytes();
for(byte s : line2){
array2[k]=s;
k++;}
}
return array2;
}
this work with me BUT please can any one tell me which one better this one or the other one OR the other one which provided by "fge" Because i hope to take the best and thank you for all.

You said you will read the file line by line and store them in an array, but you haven't stored them in an array. Below the line line2 = sCurrentLine.getBytes();, store line2 in an array, and then read the next line.
sCurrentLine.getBytes(); returns the content of sCurrentLine as a byte array, so every time this statement is executed, it will return the bytes of the current line and so the previous line's contents is lost. So you have to store the contents line2 in another array, before reading the next line's byte.
You could use System.arraycopy() to copy the contents of line2 and append it to the contents of the previous line using this method. You can look at System class docs to find out how to use the System.arraycopy() method. Also have a look at Appending a byte[] to the end of another byte[] to append the contents of array to another array.

i want it to read the text from file to encrypt it
Reading as text is a surefire way of getting corrupted data. Read as bytes. More on this below.
With Java 7, it is as simple as:
final Path file = Paths.get("C:\\Users\\just\\Desktop\\message.txt");
final byte[] content = Files.readAllBytes(file);
Why corruption?
first of all, a BufferedReader's .readLine() strips newlines; the content you will encrypt will therefore not be the same;
second, you don't specify an encoding with which to read the file, and you don't specify an encoding to encode to bytes; and the JVM can choose to use a different default encoding and file encoding. Imagine what would happen if you read the file in windows-1252 and decoded them using UTF-8.
More generally:
when you "read a string" from a file, what is read is not characters; those are bytes. And a CharsetDecoder will then decode this sequence of bytes into a sequence of chars (possibly with information loss);
when you "write a string" to a file, what is written is not characters; again, those are bytes. And a CharsetEncoder will encode this sequence of chars into a sequence of bytes.

Related

characters not appearing when I print when I import a file?

I'm importing a file into my code and trying to print it. the file contains
i don't like cake.
pizza is good.
i don’t like "cookies" to.
17.
29.
the second dont has a "right single quotation" and when I print it the output is
don�t
the question mark is printed out a blank square. is there a way to convert it to a regular apostrophe?
EDIT:
public class Somethingsomething {
public static void main(String[] args) throws FileNotFoundException,
IOException {
ArrayList<String> list = new ArrayList<String>();
File file = new File("D:\\project1Test.txt");//D:\\project1Test.txt
if(file.exists()){//checks if file exist
FileInputStream fileStream = new FileInputStream(file);
InputStreamReader input = new InputStreamReader(fileStream);
BufferedReader reader = new BufferedReader(input);
String line;
while( (line = reader.readLine()) != null) {
list.add(line);
}
for(int i = 0; i < list.size(); i ++){
System.out.println(list.get(i));
}
}
}}
it should print as normal but the second "don't" has a white block on the apostrophe
this is the file I'm using https://www.mediafire.com/file/8rk7nwilpj7rn7s/project1Test.txt
edit: if it helps even more my the full document where the character is found here
https://www.nytimes.com/2018/03/25/business/economy/labor-professionals.html
It’s all about character encoding. The way characters are represented isn't always the same and they tend to get misinterpreted.
Characters are usually stored as numbers that depend on the encoding standard (and there are so many of them). For example in ASCII, "a" is 97, and in UTF-8 it's 61.
Now when you see funny characters such as the question mark (called replacement character) in this case, it's usually that an encoding standard is being misinterpreted as another standard, and the replacement character is used to replace the unknown or misinterpreted character.
To fix your problem you need to tell your reader to read your file using a specific character encoding, say SOME-CHARSET.
Replace this:
InputStreamReader input = new InputStreamReader(fileStream);
with this:
InputStreamReader input = new InputStreamReader(fileStream, "SOME-CHARSET");
A list of charsets is available here. Unfortunately, you might want to go through them one by one. A short list of most common ones could be found here.
Your problem is almost certainly the encoding scheme you are using. You can read a file in most any encoding scheme you want. Just tell Java how your input was encoded. UTF-8 is common on Linux. Windows native is CP-1250.
This is the sort of problem you have all the time if you are processing files created on a different OS.
See here and Here
I'll give you a different approach...
Use the appropriate means for reading plain text files. Try this:
public static String getTxtContent(String path)
{
try(BufferedReader br = new BufferedReader(new FileReader(path)))
{
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
return sb.toString();
}catch(IOException fex){ return null; }
}

Deleting first five lines of a text file

I'm trying to delete the first 5 lines of a text file that match five values stored in an array. Here's what I have so far...
void write(String[] activecode) throws IOException
{
File productcodes = new File("productcodes.txt");
String charset = "UTF-8";
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(productcodes), charset));
File temp = File.createTempFile("productcodes", ".txt", productcodes.getParentFile());
PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(temp), charset));
int counter = 0;
for (String line; (line = reader.readLine()) != null && counter != activecode.length;)
{
line = line.replace(activecode[counter], "");
writer.println(line);
counter++;
}
reader.close();
writer.close();
productcodes.delete();
temp.renameTo(productcodes);
}
Also for reference, here is what the text file looks like...
BH390311ED6911-D8P8-BG7X
BH390311ED6912-GXKQ-BQ9V
BH390311ED6913-B6JF-55YG
BH390311ED6914-7B56-W37Y
BH390311ED6915-HPDW-V949
BH390311ED6916-3XX4-NDSN
BH390311ED6917-JH4M-PK6B
BH390311ED6918-WQKJ-5TKG
BH390311ED6919-TKS3-WHG3
BH390311ED6920-QTJV-9F43
BH390311ED6921-D45V-GHNG
BH390311ED6922-JH5F-4KXM
BH390311ED6923-6NQM-WSWF
BH390311ED6924-DMFD-BTN6
BH390311ED6925-7883-JG67
BH390311ED6926-3GRN-W7YT
BH390311ED6927-CBKB-47RW
The array is already saved as the first five values of the text file.
Any got any ideas on why the output is the text file with only the first three values remaining? I'm very new to Java (as you can probably tell :D)
EDIT:
The contents of the array activecode[] is:
BH390311ED6911-D8P8-BG7X
BH390311ED6912-GXKQ-BQ9V
BH390311ED6913-B6JF-55YG
BH390311ED6914-7B56-W37Y
BH390311ED6915-HPDW-V949
My desired output would be:
BH390311ED6916-3XX4-NDSN
BH390311ED6917-JH4M-PK6B
BH390311ED6918-WQKJ-5TKG
BH390311ED6919-TKS3-WHG3
BH390311ED6920-QTJV-9F43
BH390311ED6921-D45V-GHNG
BH390311ED6922-JH5F-4KXM
BH390311ED6923-6NQM-WSWF
BH390311ED6924-DMFD-BTN6
BH390311ED6925-7883-JG67
BH390311ED6926-3GRN-W7YT
BH390311ED6927-CBKB-47RW
Which is the original file minus the contents of the array.
This is the loop in your code:
for (String line; (line = reader.readLine()) != null && counter != activecode.length;)
{
line = line.replace(activecode[counter], "");
writer.println(line);
counter++;
}
Here's what it does: For counter = 0, 1, 2, 3, and 4, it reads a line from the input file. line.replace(activecode[counter],"") will look for the code from activecode in the input line. If it finds it, it removes it from the line. If the entire line equals the entire activecode[counter] element, then the line is replaced by an empty string "".
But then you write the line to the file. If your intent was to delete the lines from the file, this doesn't do that. line is now (probably) an empty string, and writer.println(line) will write an empty string to the output file. I'm not entirely sure what your needs are; it may be something like
if (!line.equals(activecode[counter]))
writer.println(line);
which will write out the line unless it equals activecode[counter], and if they're equal, it will skip the line and not write anything out. However, I'm not clear on what the exact requirements are--for instance, if the third line in the file equals activecode[0], what's supposed to happen? So I don't know whether the above is the correct solution. I think you'll need to define (at least for yourself) exactly what the program is supposed to do.
Finally, after this loop is done, your program doesn't read any more of the input. That is, it only reads the first five lines. Then it closes the input and output files. If you need to read the rest of the input file and copy it to the output file, you'll need to write another loop to do that.

Java StringBuffer: replace the content from a starting index to the end of a line

I have content of a file in a StringBuffer. The content of the file includes many lines (not on a single line). I want to edit the content of a line from index 4 (just for example) to the end of that line. I use replace() to edit the content of the StringBuffer.
The point is that the replace method has parameters such as starting index and ending index. But I don't know what is the ending index since each line have different number of characters
I think of using str.indexOf("\n") to find the ending index of the line, but then the file have many lines, so it will return incorrect results.
this is the readFile() if u need to read the code
Thank you
public StringBuffer readFile(){ //read file line by line
File f = getFilePath(fileName);
StringBuffer sb = new StringBuffer();
String textinLine;
try {
FileInputStream fs = new FileInputStream(f);
InputStreamReader in = new InputStreamReader(fs);
BufferedReader br = new BufferedReader(in);
while (true){
textinLine = br.readLine();
if (textinLine == null) break;
sb.append(textinLine+ "\n");
}
fs.close();
in.close();
br.close();
} ... // just some catch statements heres
}
Use String.indexOf() as you indicated, but pass in the starting position, e.g. indexOf('\n', 4);
I agree with Jim's idea, why not process string before appending it to StringBuffer.
By the way, I think you can use indexOf(String str, int fromIndex) function to parse StringBuffer, and each time when you get '\n', you can set an offset value, then next time when you get the next \n, you can just let index value plus the offset.

Counting Words and Newlines In A File Using Java?

I am writing a small java app which will scan a text file for any instances of particular word and need to have a feature whereby it can report that an instance of the word was found to be the 14th word in the file, on the third line, for example.
For this i tried to use the following code which i thought would check to see whether or not the input was a newline (\n) character and then incerement a line variable that i created:
FileInputStream fileStream = new FileInputStream("src/file.txt");
DataInputStream dataStream = new DataInputStream(fileStream);
BufferedReader buffRead = new BufferedReader(new InputStreamReader(dataStream));
String strLine;
String Sysnewline = System.getProperty("line.separator");
CharSequence newLines = Sysnewline;
int lines = 1;
while ((strLine = buffRead.readLine()) != null)
{
if(strLine.contains(newLines))
{
System.out.println("Line Found");
lines++;
}
}
System.out.println("Total Number Of Lines In File: " + lines);
This does not work for, it simply display 0 at the end of this file. I know the data is being placed into strLine during the while loop as if i change the code slightly to output the line, it is successfully getting each line from the file.
Would anyone happen to know the reason why the above code does not work?
Read the javadocs for readLine.
Returns:
A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached
readLine() strips newlines. Just increment every iteration of the loop. Also, you're overcomplicating your file reading code. Just do new BufferedReader(new FileReader("src/file.txt"))

Extracting UTF-16 encoded file from ZIP archive in Java

In the last section of the code I print what the Reader gives me. But its just bogus, where did I go wrong?
public static void read_impl(File file, String targetFile) {
// Create zipfile input stream
FileInputStream stream = new FileInputStream(file);
ZipInputStream zipFile = new ZipInputStream(new BufferedInputStream(stream));
// Im looking for a specific file/entry
while (!zipFile.getNextEntry().getName().equals(targetFile)) {
zipFile.getNextEntry();
}
// Next step in api requires a reader
// The target file is a UTF-16 encoded text file
InputStreamReader reader = new InputStreamReader(zipFile, Charset.forName("UTF-16"));
// I cant make sense of what this print
char buf[] = new char[1];
while (reader.read(buf, 0, 1) != -1) {
System.out.print(buf);
}
}
I'd guess that where you went wrong was believing that the file was UTF-16 encoded.
Can you show a few initial byte values if you don't decode them?
Your use of a char array is a bit pointless, though at first glance it should work. Try this instead:
int c;
while ((c = reader.read()) != -1) {
System.out.print((char)c);
}
If that does not work either, then perhaps you got the wrong file, or the file does not contain what you think it does, or the console can't display the characters it contains.

Categories

Resources