Storing a String as a file in database in java - java

I want to turn the content of a String variable into (I don't know the the correct term) a file and store it in my database. I do not need the file physically and only need it stored in the database so I can download it later in the Frontend.
I want the operation to happen automatically in the Backend (Rest API turns a String variable into a file with the extension .pem and stores it in the database). Is it possible ? Any help is appreciated.

maybe what I think is you want to store some data in a File.If wrong, please inform me.
You need to import some packages for that :-
import java.io.File;
import java.io.Scanner;
import java.io.FileWriter;
import java.util.Arrays;
Use the following code :-
public void writetoFile(String pathtofile, String text)
{
try{
File file = new File(pathtofile);
FileWriter fw = new FileWriter(file);
fw.write(text);
fw.close();
}
catch(IOException e){
System.out.println(e);
}
}
//If you want to read content from the file, you can get all lines in an array or other method you wish.
public String [] readfromFile(String path){
try{
File file = new File(path);
Scanner scan = new Scanner(file);
String [] out = new String[1];
int i=0;
while(scan.hasNextLine()){
out[i]=scan.nextLine();
i++;
out = Arrays.copyOf(out,out.legnth+1);
}
}catch(IOException e){
System.out.println(e);
}
return out;
}

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- Making a File from template with layout?

What I'm trying to achieve is a program that makes a file from the template called WaarschuwingsBriefTemplate.txt (WarningLetterTemplate).The method is called with a Klant (Customer) in its parantheses.
Now when I call this method, it won't write any enters at all, even though there are enters in the Template and I'm trying to add enters in the method itself but it doesnt seem to work. Brief translation of the foreign words:
NAAM = NAME
ADRES = ADDRESS
POSTCODE = ZIP CODE
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class FileMaker {
public FileMaker(){
}
public void maakWaarschuwingsBrief(Klant k) throws IOException{
File file = new File("WaarschuwingsBriefTemplate.txt");
String newFile = "";
try{
Scanner sc = new Scanner(file);
while(sc.hasNextLine()){
String line = sc.nextLine();
if(line.contains("--NAAM--")){
line = line.replace("--NAAM--", k.getNaam())+"\n";
}
if(line.contains("--ADRES--")){
line = line.replace("--ADRES--", k.getAdres())+"\n";
}
if(line.contains("--POSTCODE--")){
line = line.replace("--POSTCODE--", k.getPostcode())+"\n";
}
newFile += line + "\n";
}
sc.close();
}catch(FileNotFoundException e){
e.printStackTrace();
}
File file2 = new File(k.getNaam().replaceAll("\\s","")+".txt");
if(!file2.exists()){
file2.createNewFile();
}
FileWriter fw = new FileWriter(file2.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(newFile);
bw.close();
}
}
`
If your template is not too big and it's ok to read the file as whole to memory maybe try https://commons.apache.org/proper/commons-lang/javadocs/api-3.1/org/apache/commons/lang3/text/StrSubstitutor.html instead of manual manipulation?
Also use http://docs.oracle.com/javase/8/docs/api/java/lang/System.html#lineSeparator-- instead of "\n"

Java -- Need help to enhance the code

I wrote a simple program to read the content from text/log file to html with conditional formatting.
Below is my code.
import java.io.*;
import java.util.*;
class TextToHtmlConversion {
public void readFile(String[] args) {
for (String textfile : args) {
try{
//command line parameter
BufferedReader br = new BufferedReader(new FileReader(textfile));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
Date d = new Date();
String dateWithoutTime = d.toString().substring(0, 10);
String outputfile = new String("Test Report"+dateWithoutTime+".html");
FileWriter filestream = new FileWriter(outputfile,true);
BufferedWriter out = new BufferedWriter(filestream);
out.write("<html>");
out.write("<body>");
out.write("<table width='500'>");
out.write("<tr>");
out.write("<td width='50%'>");
if(strLine.startsWith(" CustomerName is ")){
//System.out.println("value of String split Client is :"+strLine.substring(16));
out.write(strLine.substring(16));
}
out.write("</td>");
out.write("<td width='50%'>");
if(strLine.startsWith(" Logged in users are ")){
if(!strLine.substring(21).isEmpty()){
out.write("<textarea name='myTextBox' cols='5' rows='1' style='background-color:Red'>");
out.write("</textarea>");
}else{
System.out.println("else if block:");
out.write("<textarea name='myTextBox' cols='5' rows='1' style='background-color:Green'>");
out.write("</textarea>");
} //closing else block
//out.write("<br>");
out.write("</td>");
}
out.write("</td>");
out.write("</tr>");
out.write("</table>");
out.write("</body>");
out.write("</html>");
out.close();
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
e.printStackTrace();
}
}
}
public static void main(String args[]) {
TextToHtmlConversion myReader = new TextToHtmlConversion();
String fileArray[] = {"D:/JavaTesting/test.log"};
myReader.readFile(fileArray);
}
}
I was thinking to enhance my program and the confusion is of either i should use Maps or properties file to store search string. I was looking out for a approach to avoid using substring method (using index of a line). Any suggestions are truly appreciated.
From top to bottom:
Don't use wildcard imports.
Don't use the default package
restructure your readFile method in more smaller methods
Use the new Java 7 file API to read files
Try to use a try-block with a resource (your file)
I wouldn't write continuously to a file, write it in the end
Don't catch general Exception
Use a final block to close resources (or the try block mentioned before)
And in general: Don't create HTML by appending strings, this is a bad pattern for its own. But well, it seems that what you want to do.
Edit
Oh one more: Your text file contains some data right? If your data represents some entities (or objects) it would be good to create a POJO for this. I think your text file contains users (right?). Then create a class called Users and parse the text file to get a list of all users in it. Something like:
List<User> users = User.parse("your-file.txt");
Afterwards you have a nice user object and all your ugly parsing is in one central point.

Modify or Delete Data in a File

Today I was trying the algorithm for modifying and deleting data inside a file using Java in Windows platform.
1st : create a temporaryFile
2nd : write the data you wanted inside the originalFile into a String and to the temporaryFile
3rd : rename temporaryFile to originalFile.
The Code:
import java.io.File;
import java.io.IOException;
import java.io.FileWriter;
import java.util.Scanner;
import java.io.FileNotFoundException;
public class testing{
private static String temp;
public static void main(String [] args)
{
try{
File tempFile = File.createTempFile("haha\\temporary", ".txt"); //create a temporary file in haha folder
FileWriter writer = new FileWriter(tempFile);
Scanner input = new Scanner(new File("haha\\testing.txt")); //get input from testing.txt
temp = input.next();
writer.write(temp);
writer.close();
File origFile = new File("haha\\testing.txt");
tempFile.renameTo(origFile);
}
catch ( FileNotFoundException fileNotFoundException ){}
catch(IOException ioException){}
}
}
In the above code , the textFile to be edited is located inside a folder name haha which is located inside another folder together with the testing.class.I've tried this code to no avail , the originalTextFile has no changes .
If you have your file in the same directory, you don't need to pass the path to the File constructor.
Scanner input = new Scanner(new File("testing.txt"));
This should do it.
You need to close the Scanner object to make the changes, the underlying operating system has a file lock that must be released.
input.close();
File origFile = new File("haha\\testing.txt");

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

Categories

Resources