Suppose I have a file called "Bill.txt".
The format:
ItemType ItemName Price
Now I want to add a new Description field. This description must be written next to the price.
The problem is, how to determine the position where to write it.
Yeah I agree with user2085282. You could read in the file using:
BufferedReader in = new BufferedReader(new FileReader("Bill.txt"));
For each line, the Reader reads, add like a semicolon or some character that should not be in the original file. Then in array split the string based on that character.
while ((line = in.readLine()) != null) {
//string = line + semicolon
// then set an array to split(;)
}
Then in another loop have like result += array[i] + description;
Then write the string in a new file
Related
I want to be able to read an entire text file that has empty lines between text. Every solution I try to implement seems to stop reading after it reaches an empty line. I want to be able to read an entire text file, including empty lines, and store the contents in a String. This is what I have now. I included two implementations. How can I alter either of the implementations to continue reading after an empty line? Also, I want the empty lines in the text file to be included in the String that it is being stored in.
File templateFile = new File(templatePath);
String oldContent = "";
BufferedReader reader = new BufferedReader(new FileReader(templateFile));
//Implementation 1
String line = reader.readLine();
while(line != null) {
oldContent = oldContent + line + System.lineSeparator();
line = reader.readLine();
}
/* Implementation 2
Scanner sc = new Scanner(templateFile);
while(sc.hasNext()) {
oldContent = sc.nextLine();
} */
Using java 11 java.nio.file.Files.readString()
oldContent = Files.readString(Paths.get(templatePath));
I am reading text from a file and I have been having trouble trying to read List 1 and List 2 into 2 different String . The * indicates where the first list ends. I have tried using arrays but the array only stores the last * symbol.
List 1
Name: Greg
Hobby 1: Swimming
Hobby 2: Football
*
List 2
Name: Bob
Hobby 1: Skydiving
*
Here's what I tried so far:
String s = "";
try{
Scanner scanner = new Scanner(new File("file.txt"));
while(scanner.hasnextLine()){
s = scanner.nextLine();
}
}catch(Exception e){
e.printStackTrace}
String [] array = s.split("*");
String x = array[0];
String y = array[1];
Your code has multiple issues like #Henry said that your string contains only the last line of the file and also you misunderstood the split() because it takes a RegularExpression as a parameter.
I would recommend you to use the following example because it works and is a lot faster than your approach.
Kick-Off example:
// create a buffered reader that reads from the file
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("test.txt")));
// create a new array to save the lists
ArrayList<String> lists = new ArrayList<>();
String list = ""; // initialize new empty list
String line; // initialize line variable
// read all lines until one becomes null (the end of the file)
while ((line = reader.readLine()) != null) {
// checks if the line only contains one *
if (line.matches("\\s*\\*\\s*")) {
// add the list to the array of lists
lists.add(list);
} else {
// add the current line to the list
list += line + "\r\n"; // add the line to the list plus a new line
}
}
Explanation
I'm going to explain special lines that are hard to understand again.
Looking at the first line:
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("test.txt")));
This line creates a BufferedReader that is nearly the same like a Scanner but it's a lot faster and hasn't as much methods as a Scanner. For this usage the BufferedReader is more than enough.
Then it takes an InputStreamReader as a parameter in the constructor. This is only to convert the following FileInputStream to a Reader.
Why should one do that? That's because an InputStream ≠ Reader. An InputStream returns the raw values and a Reader converts it to human readable characters. See the difference between InputStream and Reader.
Looking at the next line:
ArrayList<String> lists = new ArrayList<>();
Creates a variable array that has methods like add() and get(index). See the difference of arrays and lists.
And the last one:
list += line + "\r\n";
This line adds the line to the current list and adds a new line to it.
"\r\n" Are special characters. \r ends the current line and \n creates a new line.
You could also only use \n but adding \r in front of it is better because this supports more Os's like Linux can have problems with it when \r misses.
Related
Using BufferedReader to read Text File
The error I get when I change list1[0] to list1[1]:
I am doing a progam that prints from a file using RDF model in java, I wanted to let the object to be as a Sting but i couldn’t find a way for it, I tried to make by using the 2-d array to let it reads from the file and print the data into the output screen. However, it doesn't work and I couldn't figure out the reason.
Here is my code:
String synonyms =null;
try {
File file1 = new File("Data/9687.txt");
FileReader fileReader1 = new FileReader(file1);
BufferedReader bufferedReader1 = new BufferedReader(fileReader1);
StringBuffer stringBuffer = new StringBuffer();
String line1;
System.out.println("Proteins & Synonyms:");
while ((bufferedReader1.readLine()) != null) {
line1 = bufferedReader1.readLine();
String[] list1 = line1.split(“/t”)
synonyms=model1.expandPrefix(list1[0]);
proteinG.addProperty(hasSynonyms,synonyms);
And here is the OUTPUT message shown:
<https://Bio2cv.net/ENSP000003488> <hasSynonyms> "ENSP000003488” .
The output for the resource is the same as the string.
Is the synonym name in the second column of the input file?
If so, you are using bad index 0 here:
synonyms=model1.expandPrefix(list1[0]);
Change it to 1 and also remove the model1.expandPrefix() call if you want a plain string literal:
synonyms=list1[1];
For skipping invalid lines (without tab character) change the code after the split() call. Check the length of the list1 array:
String[] list1 = line1.split("\t");
if (list1.length < 2) continue;
You are also reading two lines form the input instead of one.
Change this code:
while ((bufferedReader1.readLine()) != null) {
line1 = bufferedReader1.readLine();
to this:
while ((line1 = bufferedReader1.readLine()) != null) {
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.
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"))