Im creating a java app in which some text is to be stored in a text file. But store function will run in a loop where every cycle will fetch data from other classes and store in the text file. I want that my text file should store data on each cycle just like you create log. here is some piece of code:
public void store(){
File file = new File("PaperRecord.txt");
try{
PrintWriter fout = new PrintWriter(file);
fout.println("Paper Name: " + super.getpSame());
fout.println("Paper Size: " + super.getpSize());
fout.println("Paper Year: " + super.getpYear());
fout.println("Paper Author: " + super.getpAuthor());
fout.println("Paper Description: " + getpDesc());
fout.println("Paper Signature: " + getpSign());
fout.println("Email: " + getPEmail());
fout.println("");
}
catch(FileNotFoundException e){
//do nothing
}
}
Calling store function from main using loop:
while(!q.isEmpty()){
Papers temp = q.remove();
temp.print();
temp.store();
}
THe problem currently with this code is that the code create new file paperrecord each time or overrite existing. I want the same file to be increased and updated downward (more text added)
Files class is your friend dear.
try {
Files.write(Paths.get("PaperRecord.txt"), "new text appended".getBytes(), StandardOpenOption.APPEND);
}catch (IOException e) {
//exception handling left as an exercise for the reader
}
Or,a sample working code:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class AppendToFileExample {
private static final String FILENAME = "E:\\test\\PaperRecord.txt";
public static void main(String[] args) {
BufferedWriter bw = null;
FileWriter fw = null;
try {
String data = " This is new content";
File file = new File(FILENAME);
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
// true = append file
fw = new FileWriter(file.getAbsoluteFile(), true);
bw = new BufferedWriter(fw);
bw.write(data);
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bw != null)
bw.close();
if (fw != null)
fw.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
Related
I tried to hide and unhide a text file. I can hide only but when I tried to unhide, I get an error message.
try {
//Hide file;
Process process = Runtime.getRuntime().exec("cmd.exe /c attrib +h test.txt");
//wait for process to get over (i.e. for file hiding)
process.waitFor();
} catch (Exception e) {
e.getMessage();
}
//Now, let's test whether file has been hidden or not
boolean fileHidden = fileToBeHidden.isHidden();
if (fileHidden) {
System.out.println(fileName + " is hidden ");
} else {
System.out.println(fileName + " isn't hidden ");
}
this method hide file correctly but I couldn't unhide it again
Try this for hide and unhide files.
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Test {
public static void main(String[] args) {
Test.fileProcess("test.txt", true);
Test.fileProcess("test.txt", false);
}
public static void fileProcess(String fileName, boolean hide) {
try {
// you can change your full
String filePath = System.getProperty("user.dir")
+ File.separator
+ "files"
+ File.separator + fileName;
File f = new File(filePath);
if(!f.exists() && !f.isDirectory()) {
System.out.println(fileName + " file is not exist ");
return;
}
Path file = Paths.get(filePath);
Files.setAttribute(file, "dos:hidden", hide);
f = new File(filePath);
boolean fileHidden = f.isHidden();
if (fileHidden) {
System.out.println(fileName + " is hidden ");
} else {
System.out.println(fileName + " isn't hidden ");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output like this:
test.txt is hidden
test.txt isn't hidden
I had a question regarding the File.io library. So in a class I had an assignment The Class Assignment
And I got stuck writing the part of the assignment where I need to add the ints into the output file. Here is my code right here,
import java.io.*;
import java.util.Scanner;
public class JH1_00668860 {
public static void printToScreen(String filename) {
Scanner scan = null;
try {
FileInputStream fis = new FileInputStream(filename);
scan = new Scanner(fis);
while (scan.hasNextLine()) {
System.out.println(scan.nextLine());
}
} catch (FileNotFoundException e) {
System.out.println("printToScreen: can't open: " + filename);
} finally {
if (scan != null)
scan.close();
}
}// end of prin
public static void process(String inputFilename) {
String fileoutputname = null;
FileInputStream file = null;
Scanner scan = null;
FileOutputStream outputFilename = null;
OutputStream ps = null;
try {
file = new FileInputStream(inputFilename);
scan = new Scanner(file);
fileoutputname = scan.next();
System.out.println(fileoutputname + "asfasdfasdfasdf");
outputFilename = new FileOutputStream(fileoutputname);
ps = new FileOutputStream(fileoutputname);
if (scan.hasNextInt() && scan.nextInt() >= 0) {
System.out.println(scan.nextInt() + "asfs");
ps.write(scan.nextInt());
} else {
System.out.println("You have ran out of data or you have a bad value");
}
System.out.println("A file was created");
} catch (FileNotFoundException e) {
System.out.println("You ran into an exception :" + e);
} catch(IOException e) {
System.out.println("You ran into an exception :" + e);
} finally {
try {
if (file != null) {
file.close();
}
if (outputFilename != null) {
outputFilename.close();
}
if (ps != null) {
ps.close();
}
// FileInputStream st = new FileInputStream(fileoutputname);
// int contents = st.read();
// while (scan.hasNextInt()) {
// System.out.print(contents);
// }
if (scan != null) {
scan.close();
}
printToScreen(fileoutputname);
} catch (IOException e) {
System.out.println("there was an exception");
}
}
}
public static void main(String args[]) {
process("file2.txt");
}
}
When I run it the console shows This
And then I go to the file on my computer named niceJob.txt which is starting as an empty file, Eclipse then says it is going to be changed, but then when i "reload" nothing shows up.
Can anyone help me debug this bug(or if it is some other thing that is happening?) Any help would be appreciated. Thanks
After your code ps.write(scan.nextInt()); try to put ps.write.flush(); or ps.flush();
EDIT:
If it still doesn't work add imports:
import java.io.BufferedWriter;
import java.io.FileWriter;
and change ps.write(scan.nextInt()); to
BufferedWriter writer = new BufferedWriter(new FileWriter(inputFilename));
writer.write(Integer.toString(scan.nextInt));
writer.newLine();
writer.flush();
I need to input a line of text into the code and have it print that text to the file in all upper came, all lower case, and reverse. I know how to do this with string, but cannot figure out how to get it to print to the file this way. I do not need help with getting the text to print in the output but getting it to print all these ways to the actual PrintToFile.txt without actually inputting it all those different ways.
import java.io.FileNotFoundException;
import java.lang.SecurityException;
import java.util.*;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class PrintToFile { //open class
private static Formatter output;
public static void main (String args[]) throws IOException { //open main
openFile();
addRecords();
closeFile();
BufferedReader printFile = new BufferedReader(new FileReader("YoastReginaITM251Project9.txt"));
for (String line; (line = printFile.readLine()) != null;) { //open for
System.out.println("Text: " + line);
System.out.println("Text in Upper Case: " + line.toUpperCase());
System.out.println("Text in Lower Case: " + line.toLowerCase());
System.out.println("Text in Reverse Case: " + line);
} //close for
} //close main
public static void openFile() { //open openFile
try { //open try
output = new Formatter("PrintToFile.txt"); //open file
} //close try
catch (SecurityException securityException) { //open catch
System.err.println("Write permission denied. Terminating.");
System.exit(1);
} //close catch
catch (FileNotFoundException fileNotFoundException) { //open catch
System.err.println("Error opening file. Terminating.");
System.exit(1);
} //close catch
} //close openFile
public static void addRecords() { //open addRecords
try { //open try
output.format("%s", input.nextLine());
} //close try
catch (FormatterClosedException formatterClosedException) { //open catch
System.err.println("Error writing to file. Terminating.");
} //close catch
catch (NoSuchElementException elementExpcetion) { //open catch
System.err.println("Invalid input. Please try again.");
input.nextLine();
} //close catch
} //close AddRecords
public static void closeFile() { //open closeFile
if (output != null)
output.close();
} //close closeFile
} //close class
String input = "MagicString";
String upperCase = input.toUpperCase();
String lowerCase = input.toLowerCase();
StringBuilder sb = new StringBuilder();
sb.append(input);
String reversedString = sb.reverse().toString();
You can use the StringBuilder class (https://docs.oracle.com/javase/tutorial/java/data/buffers.html) to create new strings as you like, then print those to file.
The simple way is:
Read from a file into a string.
Apply toUpperCase() and store it into another string.
Apply toLowerCase() and store it into another string.
Apply reverse()[own created method] and store it into another string.
Then write all these strings into the destination file.
Here is the code by which you can perform the required operation.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class FileRW {
public static void main(String[] args) throws FileNotFoundException, IOException {
String filename="filename.txt";
String upper,lower,reverse,line;
upper=null;
lower=null;
reverse=null;
line=null;
FileReader fileReader=new FileReader(filename);
BufferedReader bufferedReader=new BufferedReader(fileReader);
while((line=bufferedReader.readLine())!=null)
{
upper=line.toUpperCase();
lower=line.toLowerCase();
reverse=reverse(line);
writeToFile(upper,lower,reverse);
}
}
static String reverse(String test)
{ String returnString="";
int len=test.length();
for(int i=len-1;i>=0;i--)
{
returnString+=test.charAt(i);
}
return returnString;
}
static void writeToFile(String line1,String line2,String line3) throws IOException
{
String filename="content.txt";
File file =new File(filename);
//if file doesnt exists, then create it
if(!file.exists()){
file.createNewFile();
}
//true = append file
FileWriter fileWritter = new FileWriter(file.getName(),true);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
bufferWritter.write(line1);
bufferWritter.write(line3);
bufferWritter.write(line2);
bufferWritter.close();
System.out.println("Done");
}
}
Maybe you could use the Scanner and FileWriter classes as well. You can try something like this if it works for your purposes:
import java.io.*;
import java.util.*;
public class Solution{
/*
* Print a string to the output file
*/
private void print(String s, FileWriter o) {
try {
o.write(s + "\n");
} catch (IOException e) {
e.printStackTrace();
}
}
/*
* Convert the strings to uppercase,
* lowercase and reverse.
*/
private void solver(Scanner sc, FileWriter o){
while(sc.hasNextLine()) {
String s = sc.nextLine();
print(s.toUpperCase(), o);
print(s.toLowerCase(), o);
print(new StringBuilder(s).reverse().toString(), o);
}
}
/*
* Main method
*/
public static void main(String args[]){
File inFile = new File("input.txt");
File outFile = new File("output.txt");
try{
Scanner sc = new Scanner(inFile);
FileWriter o = new FileWriter(outFile);
Solution s = new Solution();
s.solver(sc, o);
sc.close();
o.close();
} catch(Exception e){
System.out.println(e);
}
}
}
I am trying to load in a file from my computer with all the words of the dictionary in the file.
When I load the file i put the words into an array of strings.
I then want to eliminate all words that have more than 9 letters in them.
I then want to save the words that are 9 letters or smaller into another separate text file.
When i try to open the new file it only has 9 words in it, yet my print to the screen on eclipse will print the all words of nine or less letters.
Can anyone help!
This is a program that was gave to me as part of the question.
import java.io.*;
public class FileIO{
public String[] load(String file) {
File aFile = new File(file);
StringBuffer contents = new StringBuffer();
BufferedReader input = null;
try {
input = new BufferedReader( new FileReader(aFile) );
String line = null;
int i = 0;
while (( line = input.readLine()) != null){
contents.append(line);
i++;
contents.append(System.getProperty("line.separator"));
}
}
catch (FileNotFoundException ex) {
System.out.println("Can't find the file - are you sure the file is in this location: "+file);
ex.printStackTrace();
}
catch (IOException ex){
System.out.println("Input output exception while processing file");
ex.printStackTrace();
}
finally {
try {
if (input!= null) {
input.close();
}
}
catch (IOException ex) {
System.out.println("Input output exception while processing file");
ex.printStackTrace();
}
}
String[] array = contents.toString().split("\n");
for(String s: array){
s.trim();
}
return array;
}
public void save(String file, String[] array) throws FileNotFoundException, IOException {
File aFile = new File(file);
Writer output = null;
try {
output = new BufferedWriter( new FileWriter(aFile) );
for(int i=0;i<array.length;i++){
output.write( array[i] );
output.write(System.getProperty("line.separator"));
}
}
finally {
if (output != null) output.close();
}
}
}
this is the class i tried to use
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.*;
public class countdown{
public static void main(String args[]){
FileIO reader = new FileIO();
Scanner scan = new Scanner(System.in);
String[] inputs = reader.load("C:/Users/Sony/Documents/dict.csv"); //Reading the File as a String array from a file called dict
String[] input = new String[inputs.length]; //new String array for strings less than 9 letters
for(int i=0;i<inputs.length;i++){
if(inputs[i].length()<=9) { //if string of index i is less than 9
input[i]=inputs[i]; //add it to the new array called input
System.out.println(input[i]); //print line to check
}
}
try{
reader.save("C:/Users/Sony/Documents/dictnew.csv",input);
//this is where i save it to the new file called dictnew.
}catch (Exception e){
System.out.println(e.getClass());
}
}
}
After reading how you want you can split rest logic remains same.
package com.srijan.playground;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class FilterLengthWords {
public static void main(String[] args) throws IOException {
BufferedReader br = null;
BufferedWriter bw = null;
try {
br = new BufferedReader(new FileReader("Sample.txt"));
bw = new BufferedWriter(new FileWriter("Output.txt"));
String tmp = null;
while((tmp=br.readLine())!=null) {
if(tmp.length()<=9) {
bw.write(tmp);
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(br!=null) {
br.close();
br=null;
}
if(bw!=null){
bw.close();
bw=null;
}
}
}
}
Thanks
So, basically it works, but it doesn't. It doesn't throw any errors, it just doesn't finish writing the file. It does read all of the lines in the file and they are all formatted correctly. I've tried debugging all of that. When debugging the "currentLine" all of the lines show up and are formatted correctly; However if I check my file that I'm writing to, it writes some of them perfectly, and then will just cut off at the end. Like the program didn't have enough time before killing itself.
My guess would be that writing takes awhile, and the program is being terminated before the file finishes writing, if that's the case, how can I avoid that?
Here's the code.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Main {
BufferedReader fileReader;
BufferedWriter fileWriter;
private Main() {
try {
fileReader = new BufferedReader(new FileReader("File/spawn-config.cfg"));
fileWriter = new BufferedWriter(new FileWriter("Dumped/world_npcs.json"));
loadFile();
} catch (IOException e) {
e.printStackTrace();
}
}
private void loadFile() {
String currentLine;
try {
fileWriter.write("[\n");
while((currentLine = fileReader.readLine()) != null) {
if(!currentLine.startsWith("//") && !currentLine.startsWith("[")
&& !currentLine.startsWith("/*")) {
System.err.println(currentLine);
String[] array = currentLine.split("\\t");
String npcID = array[0].substring(7);
String xPos = array[1];
String yPos = array[2];
String zPos = array[3];
String walk = "false";
String radius = "0";
//-----------------------
fileWriter.write("{\n");
fileWriter.write("\"npc-id\": "+npcID+"\n");
fileWriter.write("\"position\": {\n");
fileWriter.write("\"x\": " + xPos + "\n");
fileWriter.write("\"y\": " + yPos + "\n");
fileWriter.write("\"z\": " + zPos + "\n");
fileWriter.write("},\n");
fileWriter.write("\"walking-policy\": {\n");
fileWriter.write("\"coordinate\": false, \"radius\": 0\n");
fileWriter.write("}\n},");
}
}
fileWriter.write("]");
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] params) {
new Main();
}
}
If you are ready with writing flush and close the outputstream
fileWriter.flush();
fileWriter.close();