How to edit/insert new line to html file - java

I am trying to use following code to edit html page using java.
package com.XXX.xxx.xxx
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class HTMLReading {
/**
* #param args
*/
public static void main(String[] args) {
StringBuilder contentBuilder = new StringBuilder();
try {
BufferedReader in = new BufferedReader(new FileReader("C:\\ItemDetails.html"));
String str;
while ((str = in.readLine()) != null) {
if(str.equals("<div id=\"row2\" style=\"display:none;\" ><ul>")) {
// add following lines to html
//<li><b>Comments</b></li><ul><li>Testing for comment</li></ul>
}
System.out.println(str);
}
in.close();
} catch (IOException e) {
}
}
}
On reading perticular line, I want to insert some new line to html.
//<li><b>Comments</b></li><ul><li>Testing for comment</li></ul>
I tried Append, but it adds the line at end, not at the place where I want.
And my requirement is I have to use only JAVA only for this.
Any thoughts!

You can use Java.io.BufferedWriter.newLine() method.
It's non static method, you can find some documantation here:
http://www.tutorialspoint.com/java/io/bufferedwriter_newline.htm
Also,
You better use StringBuffer and not just String, because it's an immutable object like:
StringBuffer sb = new StringBuffer();
sb.append ("<br>blabla<br>");

You could try something like this:
String str;
StringBuilder contentBuilder = new StringBuilder();
while ((str = in.readLine()) != null) {
if(str.equals("<div id=\"row2\" style=\"display:none;\" ><ul>")) {
contentBuilder.append("add your content" + str);
}
else
{
contentBuilder.append(str);
}
System.out.println(str);
}
You can store it in a String then write combined to the file over what was there.

Newlines are represented in Java as "\n". It sounds like you want your StringBuilder to contain the contents of the original file, plus the additional lines you describe. To accomplish that your code might look like:
public static void main(String[] args) {
StringBuilder contentBuilder = new StringBuilder();
try (BufferedReader in = new BufferedReader(new FileReader("C:\\ItemDetails.html"))) {
String str;
while ((str = in.readLine()) != null) {
contentBuilder.append(str);
if (str.equals("<div id=\"row2\" style=\"display:none;\" ><ul>")) {
contentBuilder.append("\n<li><b>Comments</b></li><ul><li>Testing for comment</li></ul>\n);
}
}
} catch (IOException e) {
}
System.out.println(contentBuilder.toString());
}

Related

Getting error "This method must return a result of type java.lang.String"

Suppose that file.txt only contains "Hello". When I compile the Java code, it shows
Error: This method must return a result of type java.lang.String in line5.
When I print in readTxt function, that works, it can show "Hello".
I already check the result is correctly String type, but it also shows compiler error. How can I make the return value to the main function?
import java.io.*;
import java.lang.String;
public class ReadTxtFile {
public static String readTxt(String filePath) {
try {
File file = new File(filePath);
if(file.isFile() && file.exists()) {
InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "utf-8");
BufferedReader br = new BufferedReader(isr);
String lineTxt = null;
lineTxt = br.readLine();
//System.out.println(lineTxt);
br.close();
return lineTxt;
} else {
}
} catch (Exception e) {
}
}
public static void main(String[] args) {
String filePath = "C:/file.txt";
String fileword = readTxt(filePath);
System.out.println(fileword);
}
}
You promised to return a String from your method, so you now have to do that. The only way around that promise is to throw an exception.
public static String readTxt(String filePath) { // Here you promise to return a String
try {
...
if(file.isFile() && file.exists()) {
...
return lineTxt; // Here you return a String as promised
} else {
// Here you're missing either return or throw
}
} catch (Exception e) {
// Here you're missing either return or throw
}
}
This is fundamentally a design problem - what should your method do if it fails to read the file for some reason? Return a special string like "Error"? Return null? Fail and throw and exception? Something else?
Answer that to yourself and it will be clear to you how to fix the code.
There are several best practices you should follow that will prevent future error. I have tried to cover them. Not saying mine is the perfect one, but you will get the idea.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class StackOverFlow {
public static void main(String[] args) {
try {
String sText = getFileText("C:/file.txt");
System.out.println("Text is: " + sText);
} catch (FileNotFoundException e) {
System.out.println("File not Found");
} catch (IOException e) {
System.out.println("#Error while reading text: " + e.getMessage());
}
}
private static String getFileText(String filePath) throws FileNotFoundException, IOException {
File file = new File(filePath);
String line = null;
StringBuilder stringBuilder = new StringBuilder();
String ls = System.getProperty("line.separator");
BufferedReader reader = null;
try{
reader = new BufferedReader(new FileReader(file));
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
stringBuilder.append(ls);
}
reader.close();
}finally {
reader.close();
}
return new String(stringBuilder);
}
}

Splitting a String by Comma, then put it in a Treemap

I have a file called "marathon", where I have 7 keys:
sex
time
athlete
athlete's nationality
date
city
country
splitted by a comma ",". I have to put the second key (time) in a Treemap.
At the moment I am just trying to show only the time in the console.
So here is my code:
public class Text {
#SuppressWarnings("resource")
public static void main(String[] args) throws FileNotFoundException {
try {
BufferedReader in = new BufferedReader(new FileReader("marathon"));
String str;
str = in.readLine();
while ((str = in.readLine()) != null) {
//System.out.println(str);
String[] ar=str.split(",");
System.out.println(ar[0]);
}
in.close();
} catch (IOException e) {
System.out.println("File Read Error");
}
}
}
This is what a line of the text looks like:
M, 2:30:57.6, Harry Payne, GBR, 1929-07-05, Stamford Bridge, England
When I start the program of my code example and put in System.out.println(ar[0]); a[0] shows me the first line in the console so M's and F's. But when I put a[1] there is an exception:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
As others have pointed out, you do readline twice before you get into the body of the loop, so you will miss the first line.
But you are also not checking that readline resulted in a properly formatted line. It may be an empty line or a line that in some other way does not result in an array that you expect.
So you should add an if-statement that checks that you have what you expected, like so...
public class Text {
#SuppressWarnings("resource")
public static void main(String[] args) throws FileNotFoundException {
try {
BufferedReader in = new BufferedReader(new FileReader("marathon"));
String str = "";
while ((str = in.readLine()) != null) {
String[] ar=str.split(",");
if(ar.length >= 7) {
System.out.println(ar[0] + ", " + ar[1]);
}
}
in.close();
} catch (IOException e) {
System.out.println("File Read Error");
}
}
}
Please try the code below. It's working for me.
You should have read the line only once in the while loop.
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Text {
#SuppressWarnings("resource")
public static void main(String[] args) throws FileNotFoundException {
try {
BufferedReader in = new BufferedReader(new FileReader("marathon"));
String str;
while ((str = in.readLine()) != null) {
//System.out.println(str);
String[] ar=str.split(",");
System.out.println(ar[0]);
System.out.println(ar[1]);
}
in.close();
} catch (IOException e) {
System.out.println("File Read Error");
}
}
}
SortedMap<String, String[]> map = new TreeMap<>();
Path path = Paths.get("marathon");
Files.lines(path, Charsets.defaultCharset())
.map(line -> line.split(",\\s*"))
.peek(words -> {
if (words.length != 7) {
Logger.getLogger(getClass().getName()).info("Line wrong: " + line);
}
})
.filter(words -> words.length == 7)
.forEach(words -> map.put(word[1], words));
However there are CSV reader classes out there, that can handle quoted fields with commas and such.
Java 8 just for fun
import java.io.IOException;
import java.nio.file.*;
import java.util.*;
import java.util.stream.Stream;
import static java.nio.charset.Charset.defaultCharset;
import static java.lang.System.out;
import static java.nio.file.Files.lines;
public class Main {
public static void main(String[] args) throws IOException {
Map<String, String[]> map = new TreeMap<>( );
try( Stream<String> lines = lines(Paths.get("marathon"), defaultCharset())){
lines.map(line -> line.split( "," )).forEach( entry -> map.put(entry[1], entry ));
map.values().forEach( entry -> out.println(Arrays.toString( entry )) );
}
}
}

Encoding with UTF-16 in Java

I'm trying to read/write a .txt file in UTF-16 so that I can input/output Japanese characters into/from my program. I have read many similar questions, articles and the Java Docs, virtually copied their code and still can't figure out where I am going wrong. If I output it to the console, or whenever I check the contents of the file (using the correct encoding) all I see is a '?' in place of 'あ'.
Application class:
public class App {
public static void main(String[] args) {
String[] s = {"あ"}; //A test String array
FileReader.write("unicode.txt", "UTF-16", s, false);
System.out.println("File: " + FileReader.read("unicode.txt", "UTF-16") + " Hard-coded example: あ");
}
}
FileReader class:
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.nio.charset.Charset;
public class FileReader {
public static String[] read(String fileName, String encoding) {
ArrayList<String> content = new ArrayList<String>();
try(BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(fileName), Charset.forName(encoding).newDecoder()))) {
for(String s = reader.readLine(); s != null; s = reader.readLine()) {
content.add(s);
}
reader.close();
} catch(IOException e) {
System.out.println("An IOException(Input) has been thrown.");
e.printStackTrace();
}
return convertToStringArray(content);
}
public static void write(String fileName, String encoding, String[] content, boolean append) {
try(BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName, append), Charset.forName(encoding).newEncoder()))) {
for(String s : content) {
writer.write(s);
writer.newLine();
}
writer.close();
} catch (IOException e) {
System.out.println("An IOException(appending=" + append + ") has been thrown.");
e.printStackTrace();
}
}
private static String[] convertToStringArray(ArrayList<String> list) {
String[] array = new String[list.size()];
list.toArray(array);
return array;
}
}

Why is line from file not printed in java

I'm trying to read a file in java. In that file, some string is given which I want to print. But my code prints only lines of even numbers and skips lines of odd numbers.
I searched for that in stackoverflow, but have found no solution previously answered.
My code is given below...
//main class
import java.io.IOException;
public class takingInputFrpmFile {
public static void main(String[] args) throws IOException {
String filePath = "F:/Path/in.txt";
try
{
readFile rF = new readFile(filePath);
String[] receivedArray = rF.Read();
for(int i=0;i<receivedArray.length;i++)
System.out.println(receivedArray[i]);
}
catch(IOException e)
{
System.out.println(e.getMessage());
}
}
}
// class called from main class
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class readFile {
private String path;
public readFile(String path)
{
this.path=path;
}
public String[] Read() throws IOException
{
FileReader fR = new FileReader(path);
BufferedReader bR = new BufferedReader(fR);
String[] textData = new String[110];
String check;
int i=0;
while((check = bR.readLine()) != null)
{
textData[i] = bR.readLine();
i++;
}
bR.close();
return textData;
}
}
The file contains this lines...
This is the output of my code....
What is wrong with my code? What should I change? How to get rid of printing that last nulls ? Help please... Thanks in advance...
You are first reading the line and checking it's not null, then you read another line.
while((check = bR.readLine()) != null)
{
textData[i] = check; //Changed this to check
i++;
}
That one will work.
You are currently declaring String array which has size of 110. Is your file really 110 line long? You probably should use list instead.
public List<String> Read() throws IOException
{
FileReader fR = new FileReader(path);
BufferedReader bR = new BufferedReader(fR);
List<String> textData = new ArrayList<>();
String check;
while((check = bR.readLine()) != null)
{
textData.add(check);
}
bR.close();
return textData;
}
If you really want to return string array you can use:
return textData.toArray(new String[textData.size()]);
You are reading file lines twice, one when you do
check = bR.readLine()
and other when you do
textData[i] = bR.readLine();
(Each bR.readLine() reads one line)
Try changing your loop for something like
while ((textData[i] = bR.readLine()) != null) {
i++;
}
To get rid of the nulls, you can use a List instead of using a fixed size (110) array.
I suggest the following code:
//main class
import java.io.IOException;
import java.util.List;
public class Prueba {
public static void main(String[] args) throws IOException {
String filePath = "E:/Temp/in.txt";
try {
ReadFile rF = new ReadFile(filePath);
List<String> receivedArray = rF.read();
for (String currentLine : receivedArray) {
System.out.println(currentLine);
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
//class called from main class
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class ReadFile {
private final String path;
public ReadFile(String path) {
this.path = path;
}
public List<String> read() throws IOException {
// Create an empty List to protect against NPE
List<String> textData = new ArrayList<String>();
FileReader fR = null;
BufferedReader bR = null;
try {
fR = new FileReader(path);
bR = new BufferedReader(fR);
String line;
while ((line = bR.readLine()) != null) {
textData.add(line);
}
} catch (IOException e) {
throw e;
} finally {
// Close all the open resources
bR.close();
fR.close();
}
return textData;
}
}
Anyway, as Mukit Chowdhury suggested, please respect code conventions to make your code more readable (you can Google "Java code conventions" or use a well stablished ones)
It seems you do 2 read statements. Try something like:
while((check = bR.readLine()) != null)
{
textData[i] = check;
i++;
}
your line pointer incrementing two times,
while((check = bR.readLine()) != null){
textData[i] = bR.readLine();
i++;
}
Replace bR.readLine() to check in your while loop.
while((check = bR.readLine()) != null){
textData[i] = check ;
i++;
}
You call readline twice. Your loop should read
for(; (check = br.readline()) != null; textdata[i++] = check);
Or something to that effect
In Java 8, reading all lines from a File into a List<String> is easily done using utility classes from the java.nio.file package:
try {
List<String> lines = Files.readAllLines(Paths.get("/path/to/file"));
} catch (IOException e) {
// handle error
}
It's really no longer necessary to use external libraries or to re-invent the wheel for such a common task :)
From your code sample
here
while((check = bR.readLine()) != null) {
textData[i] = bR.readLine();
i++;
}
replace it with
while((check = bR.readLine()) != null) {
textData[i] = check ;
i++;
}

Read regex from properties file in java

I have problem reading values like (\+?\s*[0-9]+\s*)+ from properties file in java, because the value , what I get with getProperty() method is (+?s*[0-9]+s*)+.
Escaping of values in properties file is not an option yet.
Any ideas?
I am pretty late to answer this question, but maybe this could help others that end up here.
Newer versions of Java (not sure which, I am using 8) support escaping of values by using \\ to represent the normal \ we are used to.
For example, in your case, (\\+?\\s*[0-9]+\\s*)+ is what you are looking for.
I think this class could be solution for the backslash problem in properties file.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
public class ProperProps {
HashMap<String, String> Values = new HashMap<String, String>();
public ProperProps() {
};
public ProperProps(String filePath) throws java.io.IOException {
load(filePath);
}
public void load(String filePath) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(filePath));
String line;
while ((line = reader.readLine()) != null) {
if (line.trim().length() == 0 || line.startsWith("#"))
continue;
String key = line.replaceFirst("([^=]+)=(.*)", "$1");
String val = line.replaceFirst("([^=]+)=(.*)", "$2");
Values.put(key, val);
}
reader.close();
}
public String getProperty(String key) {
return Values.get(key);
}
public void printAll() {
for (String key : Values.keySet())
System.out.println(key +"=" + Values.get(key));
}
public static void main(String [] aa) throws IOException {
// example & test
String ptp_fil_nam = "my.prop";
ProperProps pp = new ProperProps(ptp_fil_nam);
pp.printAll();
}
}
Just read using a classical BufferedReader instead:
final URL url = MyClass.class.getResource("/path/to/propertyfile");
// check if URL is null;
String line;
try (
final InputStream in = url.openStream();
final InputStreamReader r
= new InputStreamReader(in, StandardCharsets.UTF_8);
final BufferedReader reader = new BufferedReader(r);
) {
while ((line = reader.readLine()) != null)
// process line
}
Adapt to Java 6 if necessary...

Categories

Resources