'Storing a String as a file in database in 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.
Solution 1:[1]
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;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Prime Balpreet |