i'm stuck on this part. The aim is to take the values from an file.ini with this format
X = Y
X1 = Y1
X2 = Y2
take the Y values and replace them in a scxml file instead of the corresponding X keys, and save the new file.scxml
As you can see from my pasted code, i use the HashMap to take the key and values printed correctly, that although it seems right the code to replace the values works only for the first entry of the HashMap.
The code is currently as follows:
public String getPropValues() throws IOException {
try {
Properties prop = new Properties();
String pathconf = this.pathconf;
String pathxml = this.pathxml;
//Read file conf
File inputFile = new File(pathconf);
InputStream is = new FileInputStream(inputFile);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
//load the buffered file
prop.load(br);
String name = prop.getProperty("name");
//Read xml file to get the format
FileReader reader = new FileReader(pathxml);
String newString;
StringBuffer str = new StringBuffer();
String lineSeparator = System.getProperty("line.separator");
BufferedReader rb = new BufferedReader(reader);
//read file.ini to HashMap
Map<String, String> mapFromFile = getHashMapFromFile();
//iterate over HashMap entries
for(Map.Entry<String, String> entry : mapFromFile.entrySet()){
System.out.println( entry.getKey() + " -> " + entry.getValue() );
//replace values
while ((newString = rb.readLine()) != null){
str.append(lineSeparator);
str.append(newString.replaceAll(entry.getKey(), entry.getValue()));
}
}
rb.close();
String pathwriter = pathxml + name + ".scxml";
BufferedWriter bw = new BufferedWriter(new FileWriter(new File(pathwriter)));
bw.write(str.toString());
//flush the stream
bw.flush();
//close the stream
bw.close();
} catch (Exception e) {
System.out.println("Exception: " + e);
}
return result;
}
so my .ini file is for example
Apple = red
Lemon = yellow
it print key and values correctly:
Apple -> red
Lemon -> yellow
but replace in the file only Apple with red and not the others key
The problem lays in your control flow order.
By the time the first iteration in your for loop, which corresponds to the first entry Apple -> red, runs it would caused the BufferedReader rb to reach the end of stream, hence doing nothing for subsequent iterations.
You have then either to reinitialize the BufferedReader for each iteration, or better, inverse the looping over your Map entries to be within the BufferedReader read loop:
EDIT (following #David hints)
You should can assign the resulting replaced value to the line replacement that will be appended to the result file at each line iteration:
public String getPropValues() throws IOException {
try {
// ...
BufferedReader rb = new BufferedReader(reader);
//read file.ini to HashMap
Map<String, String> mapFromFile = getHashMapFromFile();
//replace values
while ((newString = rb.readLine()) != null) {
// iterate over HashMap entries
for (Map.Entry<String, String> entry : mapFromFile.entrySet()) {
newString = newString.replace(entry.getKey(), entry.getValue());
}
str.append(lineSeparator)
.append(newString);
}
rb.close();
// ...
} catch (Exception e) {
System.out.println("Exception: " + e);
}
return result;
}
Related
So I have this task to do, I need to expand text abbreviations from the message into their full form from the .csv file, I loaded that file into HashMap, with keys as abbreviations and values as full forms. There is a loop to iterate through the keys and if statement which replaces abbreviation to full form if it finds any. I kind of figured it out and it is working as it should but I want to send this changed String (with abbreviations expanded) somewhere else out of if statement to save the full message to the file. I know that this String exists only in this if statement but maybe there is another way of doing it? Or maybe I'm doing something wrong? I became a bit rusty with Java so maybe there is a simple explanation that I don't know about. Here is the code I have :
public class AbbreviationExpander {
static void AbrExpander(String messageBody) {
//read the .csv file
String csvFile = "textwords.csv";
String line = "";
String cvsSplitBy = ",";
String bodyOut = messageBody;
HashMap<String, String> list = new HashMap<>();
try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
while ((line = br.readLine()) != null) {
String[] abbreviatonFile = line.split(cvsSplitBy);
//load the read data into the hashmap
list.put(abbreviatonFile[0], abbreviatonFile[1]);
}
for (String key : list.keySet()) {
//if any abbreviations found then replace them with expanded version
if (messageBody.contains(key)) {
bodyOut = bodyOut.replace(key, key + "<" + list.get(key).toLowerCase() + ">");
try {
File file = new File("SMS message" + System.currentTimeMillis() + ".txt");
FileWriter myWriter = new FileWriter(file);
myWriter.write(bodyOut);
myWriter.close();
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
} catch (IOException f) {
f.printStackTrace();
}
}
}
Not sure I understood well your problem. But I think you should separate the different steps in your code.
I mean your try-catch block that writes your output should be outside the for-loop and outside the reading try-catch. And your for-loop should be outside your reading try-catch.
public class AbbreviationExpander {
static void AbrExpander(String messageBody) {
String csvFile = "textwords.csv";
String line = "";
String cvsSplitBy = ",";
String bodyOut = messageBody;
HashMap<String, String> list = new HashMap<>();
//read the .csv file
try (BufferedReader br = new BufferedReader(new FileReader(csvFile))) {
while ((line = br.readLine()) != null) {
String[] abbreviatonFile = line.split(cvsSplitBy);
//load the read data into the hashmap
list.put(abbreviatonFile[0], abbreviatonFile[1]);
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
//if any abbreviations found then replace them with expanded version
for (String key : list.keySet()) {
if (messageBody.contains(key)) {
bodyOut = bodyOut.replace(key, key + "<" + list.get(key).toLowerCase() + ">");
}
}
//output the result in your file
try {
File file = new File("SMS message" + System.currentTimeMillis() + ".txt");
FileWriter myWriter = new FileWriter(file);
myWriter.write(bodyOut);
myWriter.close();
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
This question already has answers here:
Java: How to read a text file
(9 answers)
Closed 3 years ago.
I have a problem because I don't know how to read a line from a file (I searched, I tried and nothing worked). I need it because I want to use it in my future project (list of blocked players on the server in my game). At the beginning, I save the player and the reason for the ban to the HashMap. Then I have to read this nickname and separate it from the reason and check if the nickname (parameter in the checkPlayerOnTheBanList method (String nick)) agrees with the name in the file to which I saved HashMap. Then if the name (parameter) matches with the name in the file then the player won't be able to enter to the server. Here is the content of the bannedplayers.txt file:
hacker=Cheating!
player=Swearing!
Here is the part of Server.java:
public HashMap<String, String> bannedPlayersWr = new HashMap<String, String>();
public void start(String nick) {
banPlayer("player", "Swearing!");
banPlayer("hacker", "Cheating!");
boolean player = checkPlayerOnBanMap(nick);
if (player) {
System.out.println("You are banned! Your nick: " + nick);
System.out.println("Reason: " + bannedPlayersWr.get(nick));
try {
FileWriter fstream;
BufferedWriter out;
fstream = new FileWriter("C:/Users/User/Desktop/bannedplayers.txt");
out = new BufferedWriter(fstream);
Iterator<Entry<String, String>> it = bannedPlayersWr.entrySet().iterator();
while (it.hasNext()) {
Entry<String, String> pairs = it.next();
out.write(pairs.toString() + "\n");
}
out.close();
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.out.println("Welcome to the server! Your nick: " + nick);
}
}
private void banPlayer(String nick, String reason) {
bannedPlayersWr.put(nick, reason);
}
A simple way to read a file line by line and put each line as an element in a list, hope it helps you to modify it to your need.
private List<String> readFile(String filename)
throws Exception
{
String line = null;
List<String> records = new ArrayList<String>();
// wrap a BufferedReader around FileReader
BufferedReader bufferedReader = new BufferedReader(new FileReader(filename));
// use the readLine method of the BufferedReader to read one line at a time.
// the readLine method returns null when there is nothing else to read.
while ((line = bufferedReader.readLine()) != null)
{
records.add(line);
}
// close the BufferedReader when we're done
bufferedReader.close();
return records;
}
I read about someone having troubles with BufferedReader: the reader simply do not read the first lines. I have instead the opposite problem. For example, in a text file with 300 lines, it arrives at 200, read it half of it and then the following string is given null, so it stops.
private void readerMethod(File fileList) throws IOException {
BigInteger steps = BigInteger.ZERO;
BufferedReader br = new BufferedReader(new FileReader(fileList));
String st;
//reading file line by line
try{
while (true){
st = br.readLine();
if(st == null){
System.out.println("Null string at line " + steps);
break;
}
System.out.println(steps + " - " + st);
steps = steps.add(BigInteger.ONE);
}
}catch(Exception e){
e.printStackTrace();
}
finally{
try{
br.close();
}catch(Exception e){}
}
}
The output of the previous slice of code is as expected until it reaches line 199 (starting from 0). Consider a file with 300 lines.
...
198 - 3B02D5D572B66A82F9D21EE809320DB3E250C6C9
199 - 6E2C69795CB712C27C4097119CE2C5765
Null string at line 200
Notice that, all lines have the same length, so in this output line 199 is not even complete. I checked the file text, and it's correct: it contains all 300 lines and they are all of the same length. Also, in the text there are only capitals letters and numbers, as you can see.
My question is: how can i fix this? I need that the BufferedReader read all the text, not just a part of it.
As someone asked i add here the remaining part of the code. Please notice that all capital names are constant of various type (int, string etc).
This is the method that is called by the main thread:
public void init(){
BufferedWriter bw = null;
List<String> allLines = createRandomStringLines(LINES);
try{
String fileName = "SHA1_encode_text.txt";
File logFile = new File(fileName);
System.out.println(logFile.getCanonicalPath());
bw = new BufferedWriter(new FileWriter(logFile));
for(int i = 0; i < allLines.size(); i++){
//write file
String o = sha1FromString(allLines.get(i));
//sha1FromString is a method that change the aspect of the string,
//replacing char by char. Is not important at the moment.
bw.write(o + "\n");
}
}catch(Exception e){
e.printStackTrace();
}finally{
try{
bw.close();
}catch(Exception e){}
}
}
The method that create the list of random string is the following. "SYMBOLS" is just a String contains all avaiable chars.
private List<String> createRandomStringLines(int i) {
List<String> list = new ArrayList<String>();
while(i!=0){
StringBuilder builder = new StringBuilder();
int count = 64;
while (count-- != 0) {
int character = (int)(Math.random()*SYMBOLS.length());
builder.append(SYMBOLS.charAt(character));
}
String generatedString = builder.toString();
list.add(generatedString);
i--;
}
return list;
}
Note that, the file written is totally correct.
Okay, thanks to the user ygor, i manage to resolve it. The problem was that the BufferReader stars his job when the BufferWriter isn't closed yet. It was sufficient to move the command line that require the reader to work, after the bufferWriter.close() command.
Relatively new to programming. I want to read a URL, modify the text string, then write it to a line-separated csv textfile.
The read & modify parts run. Also, outputting the string to terminal (using Eclipse) looks fine (csv, line by line), like this;
data_a,data_b,data_c,...
data_a1,data_b1,datac1...
data_a2,data_b2,datac2...
.
.
.
But I'm unable to write the same string to file - it just becomes a one-liner (see my below for-loops, attempts no. 1 & 2);
data_a,data_b,data_c,data_a1,data_b1,datac1,data_a2,data_b2,datac2...
I guess I'm looking for a way to, in the FileWriter or BufferedWriter loops, convert the string finalDataA to array string (i.e. include the string suffix "[0]") but I have not yet found such an approach that would not give errors of the type "Cannot convert String to String[]". Any suggestions?
String data = "";
String dataHelper = "";
try {
URL myURL = new URL(url);
HttpURLConnection myConnection = (HttpURLConnection) myURL.openConnection();
if (myConnection.getResponseCode() == URLStatus.HTTP_OK.getStatusCode()) {
BufferedReader in = new BufferedReader(new InputStreamReader(myConnection.getInputStream()));
while ((data = in.readLine()) != null) {
dataHelper = dataHelper + "\n" + data;
}
in.close();
String trimmedData = dataHelper.trim().replaceAll(" +", ",");
String parts[] = trimmedData.split(Pattern.quote(")"));// ,1.,");
String dataA = parts[1];
String finalDataA[] = dataA.split("</PRE>");
// parts 2&3 removed in this example
// Console output for testing purpose - This prints out many many lines of csv-data
System.out.println(finalDataA[0]);
//This returns the value 1
System.out.println(finalDataA.length);
// Attempt no. 1 to write to file - writes a oneliner
for(int i = 0; i < finalDataA.length; i++) {
try (BufferedWriter bw = new BufferedWriter(new FileWriter(pathA, true))) {
String s;
s = finalDataA[i];
bw.write(s);
bw.newLine();
bw.flush();
}
}
// Attempt no. 2 to write to file - writes a oneliner
FileWriter fw = new FileWriter(pathA);
for (int i = 0; i < finalDataA.length; i++) {
fw.write(finalDataA[i] + "\n");
}
fw.close();
}
} catch (Exception e) {
System.out.println("Exception" +e);
}
Create the BufferedWriter and the FileWriter ahead of the for loop, not every time around it.
From your code comments, finalDataA has one element, so the for-loop will be executed only once. Try splitting finalDataA[0] into rows.
Something like this:
String endOfLineToken = "..."; //your variant
String[] lines = finalDataA[0].split(endOfLineToken)
BufferdWriter bw = new BufferedWriter(new FileWriter(pathA, true));
try
{
for (String line: lines)
{
bw.write(line);
bw.write(endOfLineToken);//to put back line endings
bw.newLine();
bw.flush();
}
}
catch (Exception e) {}
I've to admit that I'm not really an expert with encoding stuff etc. I've the following problem: my program has to read an text file which contains not only std. ASCII but "special chars and languages" like "..офіціалнов назвов Російска.." So let's assume that this is the content of the file: офіціалнов назвов Російска
Now I'd like to split the whole file content in single words and create another file which list all these words in lines like:
офіціалнов
назвов
Російска
My problem is: if I put these single words into an HashMap and read the values from it -> the encoding is lost. This is my code:
final StringBuffer fileData = new StringBuffer(1000);
final BufferedReader reader = new BufferedReader(
new FileReader("fileIn.txt"));
char[] buf = new char[1024];
int numRead = 0;
while ((numRead = reader.read(buf)) != -1)
{
final String readData = String.valueOf(buf, 0, numRead);
fileData.append(readData);
buf = new char[1024];
}
reader.close();
String mergedContent = fileData.toString();
mergedContent = mergedContent.replaceAll("\\<.*?>", " ");
mergedContent = mergedContent.replaceAll("\\r\\n|\\r|\\n", " ");
final BufferedWriter out = new BufferedWriter(
new OutputStreamWriter(
new FileOutputStream("fileOut.txt")));
final HashMap<String, String> wordsMap = new HashMap<String, String>();
final String test[] = mergedContent.split(" ");
for (final String string : test)
{
wordsMap.put(string, string);
}
for (final String string : wordsMap.values())
{
out.write(string + "\n");
}
out.close();
This snippet destroys the encodig. The funny thing is: if I don't put the values into the HashMap but store them immediately into the output file like:
...
for (final String string : test)
{
out.write(string + "\n");
//wordsMap.put(string, string);
}
//for (final String string : wordsMap.values())
//{
// out.write(string + "\n");
//}
out.close();
...then it works like I expect.
What I'm doing wrong?
Try using new InputStreamReader(new FileInputStream(file), "UTF-8") and then the same thing with the output. And make sure your file is encoded in UTF-8
The hashmap can't possibly make anything to the encoding.