How to populate the output of method in text file - java

I have a method Report Dose stat in Java:
public String getReportDoseStat(){
double maxdose=getMaxDose();
String s=("Average dose:\t"+getAvDose()+"\n");
s+=("Max dose:\t"+maxdose+"\n");
s+=("Pixels 90% of max dose or more:\t"+getNmbrPixDose(maxdose*0.9)+"/"+getNmbrPixDose(0.0)+"\n");
s+=("Pixels 50% of max dose or more:\t"+getNmbrPixDose(maxdose*0.5)+"/"+getNmbrPixDose(0.0)+"\n");
s+=("Pixels 10% of max dose or more:\t"+getNmbrPixDose(maxdose*0.1)+"/"+getNmbrPixDose(0.0)+"\n");
return s;
}
I would like to write the values generated from the this code to a table written in the method:
public void writeDosesTable(String p)// writing the dose table
{
{
PrintStream fos;
try{
fos=new PrintStream(new File(p));
String s;
for(int j=0;j<nz;j++){
s="";
for(int i=0;i<nx;i++){
s+=det_els.get(j+i*nz).getDose()+";";// comma separated or Semicolon separated mentioned here
}
fos.println(s);
// prints out the stream of values in Doses table separated by Semicolon
}
fos.flush();
fos.close();
}
catch (IOException e){
e.printStackTrace();
}
//finally
//{fos.close();}
}
}
How could I possibly generate such a thing?

Instead of having getDoseTable() method you can directly print the values in a file and while writing itself format your statements with the desired seperator. Something like below:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class Test {
public static void main(String[] args) throws IOException {
String[] str = { "a", "b", "c" };
BufferedWriter wr = new BufferedWriter(new FileWriter(new File(
System.getProperty("user.dir") + File.separator + "test.csv")));
for (String string : str) {
wr.write(string + ",");
}
wr.flush();
wr.close();
}
}
Here String [] str , can be the string which you wish to write in a csv file delimited with certain delimiter and then while writing take care of where you are inserting the delimiter. Let me know if you need further assistance.

Related

Method to find a word in a file and replace a new words in a file(Java)

It couldnt replace the new word and place it in a new file.
I want to create a method that take 4 parameters, one with oldfile , one with new file, one with old word and one with new word and they are all of type string.
I also want to make it so that he case of the first letter the oldWord should be maintained when writing to the in the newFile, e.g. if oldWord was “Hit” and newWord was “Cab” then if “Hit” is found in the oldFile then “Cab” should be written to the newFile.
Im not allowed to use advanced java stuff like hashkeys and all that. Hope that enough infomaton and thank you in advance.
My code couldnt print the new words into the new file instead it just prints 4 more lines of the new words in the old file.
//////
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class part2d {
public static void main(String[] args)
{
modifyFile("test.txt","modify.txt", "Hit", "Cab");
System.out.println("done");
}
static void modifyFile(String oldfile, String newfile, String oldString, String newString)
{
File fileToBeModified = new File("modify.txt");
String oldContent = "";
BufferedReader reader = null;
FileWriter writer = null;
try
{
reader = new BufferedReader(new FileReader(fileToBeModified));
String line = reader.readLine();
while (line != null)
{
oldContent = oldContent + line + System.lineSeparator();
line = reader.readLine();
}
String newContent = oldContent.replaceAll(oldString, newString);
writer = new FileWriter(fileToBeModified,true);
writer.write(newContent);
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
try
{
reader.close();
writer.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
Both your reader and your writer are using the fileToBeModified variable. This variable is being set to modify.txt statically for both, so you're not actually reading and writing a new file, instead you're reading then appending the same file content again.
Think about what file you're creating using the BufferedReader/FileReader and the FileWriter, and consider how these are being set.

Java writes "[" and "]" to a text file instead of "[" and "]"

I'm taking an input string as Java source code, editing it a little bit, and generate a .java file in Java.
Here is my code.
BufferedWriter writer = new BufferedWriter(new FileWriter("javacode.java"));
//msg = msg.substring(4); //ignore this
String newcontent = "import java.io.BufferedWriter;import java.io.ByteArrayOutputStream;import java.io.FileWriter;import java.io.PrintStream;";
char[] content = msg.toCharArray();
int j = msg.indexOf("String[] args") + 14;
boolean inMain = false;
for (int x=0;x<content.length;x++) {
if (x == j) {
inMain = true;
if (content[j] != '{') {
j += 1;
newcontent += String.valueOf(content[x]);
continue;
}
newcontent += String.valueOf(content[x]);
String prefix = "ByteArrayOutputStream consoleStorage = new ByteArrayOutputStream();PrintStream newConsole = System.out;System.setOut(new PrintStream(consoleStorage));";
newcontent += prefix;
}
else if (content[x] == '}' && inMain) {
String post = "String str = consoleStorage.toString();try {BufferedWriter writer = new BufferedWriter(new FileWriter(\"javaoutput.txt\"));writer.write(str);writer.close();} catch (Exception e) {}";
newcontent += post;
newcontent += String.valueOf(content[x]);
inMain = false;
}
else {
newcontent += String.valueOf(content[x]);
}
}
writer.write(newcontent);
writer.close();
It may look a little bit complicated, but generally speaking, I'm adding these three pieces of code into the main method of the source code input.
//At the beginning of the program, insert the following code
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.FileWriter;
import java.io.PrintStream;
...
...
...
//At the beginning of the main method, insert the following code
ByteArrayOutputStream consoleStorage = new ByteArrayOutputStream();
PrintStream newConsole = System.out;
System.setOut(new PrintStream(consoleStorage));
...
...
...
//At the end of the main method, insert the following code
String str = consoleStorage.toString();
try {
BufferedWriter writer = new BufferedWriter(new FileWriter("javaoutput.txt"));
writer.write(str);
writer.close();
} catch (Exception e) {}
However, when I test it out, with a simple Hello World example, I got this .java file.
Here is my source code input ("msg" variable, it is a simple String)
public class myClass {
public static void main(String[] args) {
System.out.println("Hello");
}
}
Here is what I got.
(I re-formatted this file for a better look)
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.FileWriter;
import java.io.PrintStream;
public class myClass {
ByteArrayOutputStream consoleStorage = new ByteArrayOutputStream();
PrintStream newConsole = System.out;
System.setOut(new PrintStream(consoleStorage));
public static void main(String[] args) {
System.out.println("Hello");
String str = consoleStorage.toString();
try {
BufferedWriter writer = new BufferedWriter(new FileWriter("javaoutput.txt"));
writer.write(str);
writer.close();
} catch (Exception e) {}
}
}
As you can see, Java fails to put "[" and "]" into the file and write "[]" instead, and thus (probably) "int j = msg.indexOf("String[] args") + 14;" fails to locate the main method.
I tried many methods to fix this, including replacing "[" by "\\[" etc, none of them works. To be honest, I'm not even sure whether "[]" generates the problem.
Update:
I tested all contents of "msg" and "content" variable/array in different phases, by inserting the following test prints into my program.
Note:
CQ.sendPrivateMsg(msgReceiver, message) is used to send the message to the receiver, this is working appropriately.
"msg" variable is passed from the chatting software, which I can only use its API to send/receive messages, while I don't have its source code...
This program is a part of an plugin of a chatting software.
...
...
...
BufferedWriter writer = new BufferedWriter(new FileWriter("javacode.java"));
msg = msg.substring(4);
//test print 1
CQ.sendPrivateMsg(fromQQ, CC.at(fromQQ) + "\n" + msg);
String newcontent = "import java.io.BufferedWriter;import java.io.ByteArrayOutputStream;import java.io.FileWriter;import java.io.PrintStream;";
char[] content = msg.toCharArray();
//test print 2
CQ.sendPrivateMsg(fromQQ, CC.at(fromQQ) + "\n" + content[55] + content[56] + content[57] + content[58]);
//test print 3
String tempstr = new String();
for (int i=0;i<content.length;i++) {
tempstr += String.valueOf(content[i]);
}
CQ.sendPrivateMsg(fromQQ, CC.at(fromQQ) + "\n" + tempstr);
int j = msg.indexOf("String[] args") + 14;
...
...
...
The actual result is shown below
//test print 1: msg
public class myClass {
public static void main(String[] args) {
System.out.println("Hello");
}
}
//test print 2: char array, accessed each digit one by one
&#91
//test print 3: char array, concatenate in a loop and print out as a whole
public class myClass {
public static void main(String[] args) {
System.out.println("Hello");
}
}
It seems like the problem is triggered by the case when I tried to access a single value within the char array, but it is fine when I use a for loop to print it all.
Update:
I solved it, by replacing [ and other strange code in char array by [ or ].
Advice given in comment is very helpful. Appreciate!
It seems like msg is received as an HTML-encoded string.
You may use Apache Commons StringEscapeUtils.unescapeHtml4() to decode this string.

Java StringTokenizer assistance

So, I have a separate program that requires a string of numbers in the format: final static private String INITIAL = "281043765"; (no spaces) This program works perfectly so far with the hard coded assignment of the numbers. I need to, instead of typing the numbers in the code, have the program read a txt file, and assign the numbers in the file to the INITIAL variable
To do this, I'm attempting to use StringTokenizer. My implementation outputs [7, 2, 4, 5, 0, 6, 8, 1, 3]. I need it to output the numbers without the "[]" or the "," or any spaces between each number. Making it look exactly like INITIAL. I'm aware I probably need to put the [] and , as delimiters but the original txt file is purely numbers and I don't believe that will help. Here is my code. (ignore all the comments please)
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class test {
//public static String num;
static ArrayList<String> num;
//public static TextFileInput myFile;
public static StringTokenizer myTokens;
//public static String name;
//public static String[] names;
public static String line;
public static void main(String[] args) {
BufferedReader reader = null;
try {
File file = new File("test3_14.txt");
reader = new BufferedReader(new FileReader(file));
num = new ArrayList<String>();
while ((line = reader.readLine())!= null) {
myTokens = new StringTokenizer(line, " ,");
//num = new String[myTokens.countTokens()];
while (myTokens.hasMoreTokens()){
num.add(myTokens.nextToken());
}
}
System.out.println(num);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
You are currently printing the default .toString() implementation of ArrayList. Try this instead:
for (String nbr : num) {
System.out.print(nbr)
}
To get rid of the brackets, you have to actually call each item in the ArrayList. Try this just below your System.out.println
for(String number : num)
System.out.print(number);
System.out.println("");
Can you also provide sample input data?
Try Replacing space and , with empty string
line = StringUtils.replaceAll(line, “,” , “”);
line = StringUtils.replaceAll(line, “ “, “”);
System.out.println(line);

Reverse file java program

I am trying to get a program to work. The input is a source file with lines of text. The output is a target file with the original line of text but in reversed.
ex.
abcd --> dcba
efgh hgfe
1234 4321
I have looked at a couple of similar questions, but they have gone about this in a different way than I have, and that doesn't exactly solve this individual problem. I have read it through and I think I am just over thinking this. I would greatly appreciate input on why my code is not outputting at all to the target file. I made a stack trace, and it prints all the way through perfectly fine.
Thanks,
code:
(command line arguments: source2.txt target2.txt
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java. util.Scanner;
/**
This program copies one file to another.
*/
public class Reverse
{
public static void main(String[] args) throws IOException
{
try{
String source = args[0];
String target = args[1];
File sourceFile=new File(source);
Scanner content=new Scanner(sourceFile);
PrintWriter pwriter =new PrintWriter(target);
while(content.hasNextLine())
{
String s=content.nextLine();
StringBuffer buffer = new StringBuffer(s);
buffer=buffer.reverse();
String rs=buffer.toString();
pwriter.println(rs);
}
content.close();
pwriter.close();
}
catch(Exception e){
System.out.println("Something went wrong");
}
}
}
What output are you seeing??
PrintWriter suppresses IOException and sets an error flag instead; you should use an
OutputStreamWriter().
Methods in this class never throw I/O exceptions, although some of its constructors may. The client may inquire as to whether any errors have occurred by invoking checkError().
Also, don't handle an exception with "something went wrong"; at the very least dump the stack trace so you know what and where it went wrong.
That said, I would probably output each line read to the console, like so:
System.out.println("** Read ["+s+"]");
to confirm I was actually reading the file.
import java.io.*;
import java.util.*;
class Driver {
public static void main(String[] args) {
ReverseFile demo = new ReverseFile();
demo.readFile("source2.txt");
demo.reverse("target2.txt");
}
}
class ReverseFile {
// Declare a stream of input
DataInputStream inStream;
// Store the bytes of input file in a String
ArrayList<Character> fileArray = new ArrayList<Character>();
// Store file sizes to see how much compression we get
long inFileSize;
long outFileSize;
// Track how many bytes we've read. Useful for large files.
int byteCount;
public void readFile(String fileName) {
try {
// Create a new File object, get size
File inputFile = new File(fileName);
inFileSize = inputFile.length();
// The constructor of DataInputStream requires an InputStream
inStream = new DataInputStream(new FileInputStream(inputFile));
}
// Oops. Errors.
catch (FileNotFoundException e) {
e.printStackTrace();
System.exit(0);
}
// Read the input file
try {
// While there are more bytes available to read...
while (inStream.available() > 0) {
// Read in a single byte and store it in a character
char c = (char)inStream.readByte();
if ((++byteCount)% 1024 == 0)
System.out.println("Read " + byteCount/1024 + " of " + inFileSize/1024 + " KB...");
// Print the characters to see them for debugging purposes
//System.out.print(c);
// Add the character to an ArrayList
fileArray.add(c);
}
// clean up
inStream.close();
System.out.println("Done!!!\n");
}
// Oops. Errors.
catch (IOException e) {
e.printStackTrace();
System.exit(0);
}
// Print the ArrayList contents for debugging purposes
//System.out.println(fileArray);
}
public void reverse(String fileName) throws IOException {
FileWriter output = new FileWriter(fileName);
for (int i = fileArray.size() - 1; i >= 0; i++) {
try {
output.write(fileArray.get(i));
}
catch (IOException e) {
e.printStackTrace();
}
}
output.close();
}
}
That should work. If not, tell me and I'll look into the problem further.
I did some modification to your code..
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
public class Reverse
{
public static void main(String[] args) throws IOException
{
try{
// String source = args[0];
// String target = args[1];
File sourceFile=new File("C:/Users/Ruchira/Downloads/in.txt");//input File Path
File outFile=new File("C:/Users/Ruchira/Downloads/out.txt");//out put file path
Scanner content=new Scanner(sourceFile);
PrintWriter pwriter =new PrintWriter(outFile);
while(content.hasNextLine())
{
String s=content.nextLine();
StringBuffer buffer = new StringBuffer(s);
buffer=buffer.reverse();
String rs=buffer.toString();
pwriter.println(rs);
}
content.close();
pwriter.close();
}
catch(Exception e){
System.out.println("Something went wrong");
}
}
}
This will work

Read in Comma separated list of files, output without commas without iteration

I'm trying to remove the commas from the following txt file:
abcd,efgh,ijkl
mnop,qrst,uvwx
yzzz,0123,4567
8910
My code goes something like this:
public static ArrayList readFileByLine(ArrayList list, String fileName){
try{
File file = new File(fileName);
Scanner reader = new Scanner(file);
reader.useDelimiter(",");
while(reader.hasNext()){
String s = reader.next();
s= s.trim();
s= s.replaceAll("," , "");
list.add(s);
}
reader.close();
}
catch(FileNotFoundException e){ System.err.println("Error: " + e.getMessage());}
return list;
}
I'm trying not to use a regex unless absolutely necessary, if you recommend that I use a regex please explain what it does! Thanks for the help!
Your code runs fine. I think you were running into other issues, I'm not sure what. Here's the code that I used (your code with some modifications):
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args){
List<String> list = readFileByLine(new ArrayList<String>(), "/Users/hassan/Library/Containers/com.apple.TextEdit/Data/Desktop/file.text");
for(String s : list){
System.out.println(s);
}
}
public static List<String> readFileByLine(ArrayList<String> list, String fileName){
try{
File file = new File(fileName);
Scanner reader = new Scanner(file);
reader.useDelimiter(",");
while(reader.hasNext()){
String s = reader.next();
s= s.trim();
s= s.replaceAll("," , "");
list.add(s);
}
reader.close();
}
catch(FileNotFoundException e){ System.err.println("Error: " + e.getMessage());}
return list;
}
}
This code works (try it!). I should mention that the way I'm using this code, passing an ArrayList as the first argument is useless, since you can just make a new ArrayList at the beginning of the readFileByLine function. I'm not sure if you did it this way because you want to re-add strings to the array later on, so I left it alone.

Categories

Resources