I'm making a Text Editor as a side project and as of now I'm struggling by saving and loading the text's font letter, color, and decoration; in other words, I can only save a plain text. My question is, how can I save and load all of these?
private void Edit() {//This is the method where the program edits the text
StyledDocument doc = this.tpText.getStyledDocument();
Style estilo = this.tpText.addStyle("miEstilo", null);
StyleConstants.setForeground(estilo, colour); //Color
StyleConstants.setFontFamily(estilo, fontLetter);//Letter
StyleConstants.setFontSize(estilo, size);//Size
StyleConstants.setBold(estilo, bold);//Bold
StyleConstants.setItalic(estilo, italics);//Italics
StyleConstants.setUnderline(estilo, underline);//Underline
doc.setCharacterAttributes(this.tpText.getSelectionStart(), this.tpText.getSelectionEnd() - this.tpText.getSelectionStart(), this.tpText.getStyle("miEstilo"), true);//The only text that will be edited is the one that the user highlights
}
private void comboxFontsActionPerformed(java.awt.event.ActionEvent evt) {//This is one of the methods in which the program edits the text
this.fontLetter = (String) this.comboxFonts.getSelectedItem();
Edit();
}
private void mibtnSaveAsActionPerformed(java.awt.event.ActionEvent evt) {//Save as... menu item button
int saveResult = fileSelect.showSaveDialog(null);
if (saveResult == fileSelect.APPROVE_OPTION) {
saveFile(fileSelect.getSelectedFile(), this.tpText.getText());
this.mibtnSave.setEnabled(true);
}
}
public void saveFile(File file, String contents) {//Save File
BufferedWriter writer = null;
String filePath = file.getPath();
try {
writer = new BufferedWriter(new FileWriter(filePath));
writer.write(contents);
writer.close();
this.tpText.setText(contents);
currentFile = file;
} catch (Exception e) {
}
}
public void openFile(File file) {//Load File
if (file.canRead()) {
String filePath = file.getPath();
String fileContents = "";
if (filePath.endsWith(".txt")) {
try {
Scanner sc = new Scanner(new FileInputStream(file));
while (sc.hasNextLine()) {
fileContents += sc.nextLine();
}
sc.close();
} catch (FileNotFoundException e) {
}
this.tpText.setText(fileContents);
currentFile = file;
} else {
JOptionPane.showMessageDialog(null, "Only .txt files are supported.");
}
} else {
JOptionPane.showMessageDialog(null, "Could not open file...");
}
}
I don't know if i got your question right, but if your trying to save the style besides the plain text you may do the following.
save all style attributes in another file next to the text file and you can restore it when you open the text file.
Related
I have a camera that I am grabbing values pixel-wise and I'd like to write them to a text file. The newest updates for Android 12 requires me to use storage access framework, but the problem is that it isn't dynamic and I need to keep choosing files directory. So, this approach it succesfully creates my files but when writting to it, I need to specifically select the dir it'll save to, which isn't feasible to me, as the temperature is grabbed for every frame and every pixel. My temperature values are in the temperature1 array, I'd like to know how can I add consistently add the values of temperature1 to a text file?
EDIT: I tried doing the following to create a text file using getExternalFilesDir():
private String filename = "myFile.txt";
private String filepath = "myFileDir";
public void onClick(final View view) {
switch (view.getId()){
case R.id.camera_button:
synchronized (mSync) {
if (isTemp) {
tempTureing();
fileContent = "Hello, I am a saved text inside a text file!";
if(!fileContent.equals("")){
File myExternalFile = new File(getExternalFilesDir(filepath), filename);
FileOutputStream fos = null;
try{
fos = new FileOutputStream(myExternalFile);
fos.write(fileContent.getBytes());
} catch (Exception e) {
e.printStackTrace();
}
Log.e("TAG", "file: "+myExternalFile);
}
isTemp = false;
//Log.e(TAG, "isCorrect:" + mUVCCamera.isCorrect());
} else {
stopTemp();
isTemp = true;
}
}
break;
I can actually go all the way to the path /storage/emulated/0/Android/data/com.MyApp.app/files/myFileDir/ but strangely there is no such file as myFile.txt inside this directory, how come??
Working Solution:
public void WriteToFile(String fileName, String content){
File path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS);
File newDir = new File(path + "/" + fileName);
try{
if (!newDir.exists()) {
newDir.mkdir();
}
FileOutputStream writer = new FileOutputStream(new File(path, filename));
writer.write(content.getBytes());
writer.close();
Log.e("TAG", "Wrote to file: "+fileName);
} catch (IOException e) {
e.printStackTrace();
}
}
Now, I read my .txt file by telling where is this file.
I want to change to I can select a file on my computer. How can I do that?
Scanner file = new Scanner(new File("Sample.txt"));
while (file.hasNextLine()) {
String input = file.nextLine();
}
Here is a runnable you can try. Like #Verity has stipulated, use the JFileChooser. Read the comments within the following code:
public class JFileChooserWithConsoleUse {
public static void main(String[] args) {
// A JFrame used here as a backbone for dialogs
javax.swing.JFrame iFrame = new javax.swing.JFrame();
iFrame.setDefaultCloseOperation(javax.swing.JFrame.DISPOSE_ON_CLOSE);
iFrame.setAlwaysOnTop(true);
iFrame.setLocationRelativeTo(null);
String selectedFile = null;
javax.swing.JFileChooser fc = new javax.swing.JFileChooser(new java.io.File("C:\\"));
fc.setDialogTitle("Locate And Select A File To Read...");
int userSelection = fc.showOpenDialog(iFrame);
// The following code will not run until the
// FileChooser dialog window is closed.
iFrame.dispose(); // Dispose of the JFrame.
if (userSelection == 0) {
selectedFile = fc.getSelectedFile().getPath();
}
// If no file was selected (dialog just closed) then
// get out of this method (which in this demo ultimately
// ends (closes) the application.
if (selectedFile == null) {
javax.swing.JOptionPane.showMessageDialog(iFrame, "No File Was Selected To Process!",
"No File Selected!", javax.swing.JOptionPane.WARNING_MESSAGE);
iFrame.dispose(); // Dispose of the JFrame.
return;
}
// Read the selected file... 'Try With Resources' is
// used here so as to auto-close the reader.
try (java.util.Scanner file = new java.util.Scanner(new java.io.File(selectedFile))) {
while (file.hasNextLine()) {
String input = file.nextLine();
// Display each read line in the Console Window.
System.out.println(input);
}
}
catch (java.io.FileNotFoundException ex) {
System.err.println(ex);
}
}
}
In this case you need to use an JFileChooser
I had write a code by using Apache POI 3.6.
The code is use to insert paragraph ,table and image to one docx file, but as the paragraph, table and image is from different docx file, so I need to read content from different docx file then insert to the target file.
But I found the file is only readable at the first content insert, so is there any thing need to be changed?
My method defined like following:
public class DocDomGroupUtilImpl implements DocDomGroupUtil {
private FileInputStream fips;
private XWPFDocument document;
private FileOutputStream fops;
#Override
public void generateDomGroupFile(File templateFile, List<Item> items) {
// initial parameters
Map<String, String> parameters = new HashMap<String, String>();
for (Item item : items) {
parameters.put(item.getParaName(), item.getParaValue());
}
// get domGroup type
String templateFileName = templateFile.getName();
String type = templateFileName.substring(0, templateFileName.indexOf("."));
try {
fips = new FileInputStream(templateFile);
document = new XWPFDocument(fips);
// create tempt file for document domGroup, named like
// docDomGroup_<type>_<domName>.docx
String domGroupFilePath = CONSTAINTS.temptDomGroupPath + "docDomGroup_" + type + "_"
+ parameters.get("$DomGroupName_Value") + ".docx";
File domGroupFile = new File(domGroupFilePath);
if (domGroupFile.exists()) {
domGroupFile.delete();
}
domGroupFile.createNewFile();
fops = new FileOutputStream(domGroupFile, true);
// modified the groupName
// replace content
String regularExpression = "\\$(.*)_Value";
List<XWPFParagraph> paragraphs = document.getParagraphs();
for (XWPFParagraph paragraph : paragraphs) {
List<XWPFRun> runs = paragraph.getRuns();
if (runs != null) {
for (XWPFRun run : runs) {
String text = run.getText(0);
if (text != null && Pattern.matches(regularExpression, text)) {
text = parameters.get(text);
run.setText(text, 0);
}
}
}
}
document.write(fops);
close();
// copy all the information from dom related files
File dir = new File(CONSTAINTS.temptDomPath);
for (File file : dir.listFiles()) {
if (!file.isDirectory()) {
fops = new FileOutputStream(domGroupFile, true);
fips = new FileInputStream(file);
document = new XWPFDocument(fips);
document.write(fops);
}
close();
}
// clean up tempt dom folder removeAllDomFile();
removeAllDomFile();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
close();
}
}
/**
* remove all the generated tempt dom files
*/
private void removeAllDomFile() {
// loop directory and delete tempt file
File dir = new File(CONSTAINTS.temptDomPath);
for (File file : dir.listFiles())
if (!file.isDirectory()) {
file.delete();
}
}
private void close() {
try {
fips.close();
fops.flush();
fops.close();
document.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
My problem is when my showopendialog appears and I press cancel or the X on the right corner instead of loading some text in my textarea, the console shows the error of nullpointexception on my line String filename=f.getAbsolutePath();
My action open is on a menu bar.
Thank you.
JFileChooser flcFile = new JFileChooser("c:\\");
flcFile.showOpenDialog(null);
File f = flcFile.getSelectedFile();
String filename=f.getAbsolutePath();
try {
FileReader reader = new FileReader(filename);
BufferedReader br = new BufferedReader(reader);
txtPersonal.read(br, null);
br.close();
txtPersonal.requestFocus();
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, e);
}
If you close without selecting a file, you can't get the absolute path of the file. Always check if a file has been selected by the user by checking the value returned by the showOpenDialog() method. Only get the absolute path after this check.
Useful reading: The JFileChooser docs.
JFileChooser flcFile = new JFileChooser("c:\\");
int result = flcFile.showOpenDialog(null);
if (result == JFileChooser.APPROVE_OPTION) {
File f = flcFile.getSelectedFile();
String filename = f.getAbsolutePath();
try {
FileReader reader = new FileReader(filename);
BufferedReader br = new BufferedReader(reader);
txtPersonal.read(br, null);
br.close();
txtPersonal.requestFocus();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
Hello I modified your code, check the following example:
public class Main {
public static void main(String[] args) {
JFileChooser flcFile = new JFileChooser("c:\\");
int result = flcFile.showOpenDialog(null);
File f = flcFile.getSelectedFile();
if (JFileChooser.CANCEL_OPTION == result) {
System.out.println("canceled");
} else if (JFileChooser.APPROVE_OPTION== result) {
String filename = f.getAbsolutePath();
System.out.println(filename);
}else{
System.out.println(result);
}
}
}
You need to check the return value of the showOpenDialog method in order to know the selected option, I hope it help you
cheers.
I'm taking HTML file and one XSLT file as input and generating HTML output but in my folder there are multiple HTML files and I've to take each of them as input and generate the corresponding output file while XSLT input file remains same every time. Currently in my code I'm repeating the code block every time to take the input HTML file. Instead of this I want to iterate over all the HTML files in the folder and take them as input file one by one to generate the output. In my current code file names are also fixed like part_1.html but it can vary and in that case this code won't work and this will create problem. Can anyone please help out in this matter:
Thanking you!
Current Java code (Sample for two files):
public void tranformation() {
// TODO Auto-generated method stub
transform1();
transform2();
}
public static void transform1(){
String inXML = "C:/SCORM_CP/part_1.html";
String inXSL = "C:/source/xslt/html_new.xsl";
String outTXT = "C:/SCORM_CP/part1_copy_copy.html";
String renamedFile = "C:/SCORM_CP/part_1.html";
File oldfile =new File(outTXT);
File newfile =new File(renamedFile);
HTML_Convert hc = new HTML_Convert();
try {
hc.transform(inXML,inXSL,outTXT);
} catch(TransformerConfigurationException e) {
System.err.println("Invalid factory configuration");
System.err.println(e);
} catch(TransformerException e) {
System.err.println("Error during transformation");
System.err.println(e);
}
try{
File file = new File(inXML);
if(file.delete()){
System.out.println(file.getName() + " is deleted!");
}else{
System.out.println("Delete operation is failed.");
}
}catch(Exception e){
e.printStackTrace();
}
if(oldfile.renameTo(newfile)){
System.out.println("Rename succesful");
}else{
System.out.println("Rename failed");
}
}
public static void transform2(){
String inXML = "C:/SCORM_CP/part_2.html";
String inXSL = "C:/source/xslt/html_new.xsl";
String outTXT = "C:/SCORM_CP/part2_copy_copy.html";
String renamedFile = "C:/SCORM_CP/part_2.html";
File oldfile =new File(outTXT);
File newfile =new File(renamedFile);
HTML_Convert hc = new HTML_Convert();
try {
hc.transform(inXML,inXSL,outTXT);
} catch(TransformerConfigurationException e) {
System.err.println("Invalid factory configuration");
System.err.println(e);
} catch(TransformerException e) {
System.err.println("Error during transformation");
System.err.println(e);
}
try{
File file = new File(inXML);
if(file.delete()){
System.out.println(file.getName() + " is deleted!");
}else{
System.out.println("Delete operation is failed.");
}
}catch(Exception e){
e.printStackTrace();
}
if(oldfile.renameTo(newfile)){
System.out.println("Rename succesful");
}else{
System.out.println("Rename failed");
}
}
public void transform(String inXML,String inXSL,String outTXT)
throws TransformerConfigurationException,
TransformerException {
TransformerFactory factory = TransformerFactory.newInstance();
StreamSource xslStream = new StreamSource(inXSL);
Transformer transformer = factory.newTransformer(xslStream);
transformer.setErrorListener(new MyErrorListener());
StreamSource in = new StreamSource(inXML);
StreamResult out = new StreamResult(outTXT);
transformer.transform(in,out);
System.out.println("The generated XML file is:" + outTXT);
}
}
File dir = new File("/path/to/dir");
File[] htmlFiles = dir.listFiles(new FilenameFilter() {
#Override
public boolean accept(File dir, String name) {
return name.endsWith(".html");
}
});
if (htmlFiles != null) for (File html: htmlFiles) {
...
}
You have to implement something like
public class Transformation {
public static void main (String[] args){
transformation(".", ".");
}
public static void transform(String inXML, String inXSL, String outTXT, String renamedFile){
System.out.println(inXML);
System.out.println(inXSL);
System.out.println(outTXT);
System.out.println(renamedFile);
}
public static void transformation(String inFolder, String outFolder){
File infolder = new File(inFolder);
File outfolder = new File(outFolder);
if (infolder.isDirectory() && outfolder.isDirectory()){
System.out.println("In " + infolder.getAbsolutePath());
System.out.println("Out " + outfolder.getAbsolutePath());
File[] listOfFiles = infolder.listFiles();
String outPath = outfolder.getAbsolutePath();
String inPath = infolder.getAbsolutePath();
for (File f: listOfFiles) {
if (f.isFile() ) {
System.out.println("File " + f.getName());
int indDot = f.getName().lastIndexOf(".");
String name = f.getName().substring(0, indDot);
String ext = f.getName().substring(indDot+1);
if (ext != null && ext.equals("html")){
transform(f.getAbsolutePath(), inPath+File.separator+name+".xsl", outPath+File.separator+name+".txt", outPath+File.separator+name+".html");
}
}
}
}
}
}
First you should write a method that take inXML, inXSL, outTXT and renamedFile as arguments.
Then, using the list() method of the File class, that eventually take a FilenameFilter, you may iterate over the files you want to transform.
Here is a sample of FilenameFilter :
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.contains("part");
}
};
Regards
use DirectoryScanner which will make your job easier
Example of usage:
String[] includes = {"**\*.html"};
ds.setIncludes(includes);
ds.setBasedir(new File("test"));
ds.setCaseSensitive(true);
ds.scan();
System.out.println("FILES:");
String[] files = ds.getIncludedFiles();
for (int i = 0; i < files.length; i++) {
System.out.println(files[i]);
}
http://plexus.codehaus.org/plexus-utils/apidocs/org/codehaus/plexus/util/DirectoryScanner.html