so here's the problem,
i stack on how to create, open, write, and read file, with this code
import java.util.*;
import java.io.*;
class class_Name{
Formatter x; // Variable: creating new file
File file = new File("file.txt"); // Variable: check file existence
//creating txt file
public void creating_file(){
try{
x = new Formatter("file.txt");
}catch(Exception e){
System.out.println("you got an error");
}
}
public int check_file(){
if(file.exists()){
return 1; // in main method, check if file already exists just pass from creating file
}else{
return 0; // in main method if return value 0, then it create new file with "public void creating_file()" method
}
}
so the problem is when i tried to write something in the file, i using class Formatter and it always format all the text data that in it before and class Formatter won't work if public int check_file() is equals to 1 because it skip from creating file using Formatter class and can't just write in the file because variable x undefined
this is the code how i write text in a file
public void recording_to_file(){
x.format(format, args);
}
and to closing file i need to handle error like this
public void close_file(){
try{
x.close();
}catch(Exception e){
file.close();
}
}
}
there was just ton of class that i need to do something with just one file, or maybe there was one simple class that can do all in one like(write, open, read, close), i am new in java, i think maybe in here i can get help, thank you
Take a look at this.
The second argument to the FileWriter costructor (true) tells it to only append data, instead of overwriting any.
import java.util.*;
import java.io.*;
class SomeClass{
Formatter x;
File file = new File("file.txt");
public void creating_file(){
try{
x = new Formatter(new FileWriter(file, true));
}catch(Exception e){
System.out.println("you got an error");
}
}
public boolean check_file(){
return file.exists();
}
}
Related
package ideat;
import java.nio.file.Paths;
import java.io.FileWriter;
import java.util.Scanner;
public class Paaohjelma {
public static void main(String[] args) {
try {
Scanner tLuk = new Scanner(Paths.get("ideat.txt"));
FileWriter tKirj = new FileWriter("ideat.txt");
for (String line = tLuk.nextLine(); line.isBlank(); tKirj.append("\n")) {
tKirj.write("textHere");
}
tKirj.close();
tLuk.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
I created a loop that goes trough the txt-file until it finds an empty line to write, however this doesn't work because when Scanner tries to read next line that is empty, java throws no next line exception. The purpose of the program is to add and save new ideas to a text file and that is why I don't want to overwrite existing lines of text.
Once you open a file you are reading in write mode, a file descriptor for reading is corrupted. It could be not corrupted, but once written something, it will be corrupted especially when what the descriptor will read overwritten.
So, you should take rewrite and replace approach:
try {
Scanner tLuk = new Scanner(Paths.get("ideat.txt"));
FileWriter tKirj = new FileWriter("ideat.txt.tmp");
while (tLuk.hasNextLine()) {
String line = tLuk.nextLine();
if (line.isBlank()) {
tKirj.write("textHere");
} else {
tKirj.write(line);
}
}
tKirj.close();
tLuk.close();
} catch (Exception e) {
Then, replace the file ideat.txt with ideat.txt.tmp.
Files.move(
Paths.get("ideat.txt.tmp"),
Paths.get("ideat.txt"),
StandardCopyOption.REPLACE_EXISTING
);
VIP group of companies introduce a new shopping mall “Le Le” . To promote the mall they had approached “6th Event” a famous commercial event organizer to organize an event of lucky draw. The organizer has to collect name, phone and email id of all the visitors during promotion time and give it to the company.
The organizer needs an automated application and wants to store records in a text file called “visitors.txt”.
Records should to be stored in the following structure
Name1,phonenumber1,emailId1;Name2,phonenumber2,emailId2;
In a record, each attributes should be separated using comma (,) and records should be separated using semi colon (;).
Create a Java Application which has two classes called Main.java and FileManager.java
In FileManager class implement the following methods [method skeletons are given]
static public File createFile() – This method should create the file and return it.
static public void writeFile(File f, String record) – In the method, first parameter is the file reference in which records to be added and second parameter is a record, This record should append in the file. [Record should be as per the given format]
static public String[] readFile(File f) – This method accept file to be read, returns all records in the file.
[Note : Don’t modify the signature of the given methods]
In Main class use the following Input and Output statements and call the needed methods from FileManager class to manipulate files.
Enter Name
John
Enter Phone Number
1234567
Enter Email
johnpeter#abc.com
Do you want to enter another record(yes/no)
yes
Enter Name
Grace
Enter Phone Number
98765412
Enter Email
gracepaul#xyz.com
Do you want to enter another record(yes/no)
no
Do you want to display all records(yes/no)
yes
John,1234567,johnpeter#abc.com
Grace,98765412,gracepaul#xyz.com
FileManager class
//import necessary packages
import java.io.*;
import java.util.*;
#SuppressWarnings("unchecked")//Do not delete this line
public class FileManager
{
static public File createFile()
{
File file =new File("visitors.txt");
try{ file.createNewFile();}
catch (IOException e)
{
e.printStackTrace(); //prints exception if any
}
return file;
}
//change the return type as per the requirement
static public void writeFile(File f, String record)
{ try {
BufferedWriter out = new BufferedWriter(
new FileWriter(f.getName(), true));
out.write(record+";");
out.close();
}
catch (IOException e) {
System.out.println("exception occoured" + e);
}
}
static public String[] readFile(File f)
{
List<String> tokens = new ArrayList<String>();
try{
File myObj = new File(f.getName());
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
// String [] arr= myReader.nextLine().split(";");
// tokens = Arrays.asList(arr);
tokens.add(myReader.nextLine());
}
myReader.close();
}
catch (FileNotFoundException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
String[] tokenArray = tokens.toArray(new String[0]);
//=tokenArray.split(";");
return tokenArray;
}
}
Main class
import java.util.*;
import java.io.FileNotFoundException;
//import necessary packages
import java.io.File;
#SuppressWarnings("unchecked")//Do not delete this line
public class Main
{
public void abcd(){
Scanner in = new Scanner(System.in);
System.out.println("Enter Name");
String name=in.next();
System.out.println("Enter Phone Number");
long phone=in.nextLong();
System.out.println("Enter Email");
String id= in.next();
FileManager f= new FileManager();
File x =f.createFile();
f.writeFile(x,name+","+phone+","+id);
System.out.println("Do you want to enter another record(yes/no)");
String choice=in.next();
if(choice.equals("yes")){
abcd();
}
if(choice.equals("no"))
{String []q=f.readFile(x);
String pl[]=q[0].split(";");
for(int i=0;i<pl.length;i++)
{
System.out.println(pl[i]);
}
System.exit(0);
}
}
public static void main(String[] args)
{
Main asd=new Main();
asd.abcd();
}
}
This program gives me desired output but not able to run all test cases.
Getting error could not append multiple files. Dont know is this.But it works perfectly on compiler. And you should at least try to code rather then simply asking someone to code.
//all test case passed
import java.io.*;
import java.util.*;
#SuppressWarnings("unchecked")//Do not delete this line
public class FileManager
{
static public File createFile()
{
File myObj = new File("visitors.txt");
try{
if(new File("visitors.txt").isFile()==false)
myObj.createNewFile();
}
catch (IOException e)
{
e.printStackTrace(); //prints exception if any
}
return myObj;//change the return type as per the requirement
}
static public void writeFile (File f, String record)
{
try
{
FileWriter fw = new FileWriter(f.getName(),true); //the true will append the new data
fw.write(record+"\n");//appends the string to the file
fw.close();
}
catch(IOException ioe)
{
System.err.println("IOException: " + ioe.getMessage());
}
}
static public String[] readFile(File f)
{
List<String> list=new ArrayList<String>();
try{
File myObj = new File(f.getName());
Scanner myReader = new Scanner(myObj);
while (myReader.hasNextLine()) {
String str=myReader.nextLine();
String[] parts = str.split(";");
for (String part : parts) {
list.add(part);
}
}
myReader.close();
}
catch(FileNotFoundException ex){}
String[] strings = list.stream().toArray(String[]::new);
return strings;
//change the return type as per the requirement
}
}
I am trying to write code for a word guessing game, and it works well when I use bufferedreader and inputstream combined. But when I try it using scanner, it cannot find the file, even though in both instances the file is in the same folder. It is in a folder called res under the src folder in my project folder(I am coding in eclipse).
import java.util.ArrayList;
import java.util.Scanner;
import java.io.File;
public class WordGen {
private final String filename = "/res/words.txt";
File file = new File(filename);
Scanner input = null;
private ArrayList<String> list = new ArrayList<>();
public WordGen() {
try {
input = new Scanner(file);
while (input.hasNextLine()) {
String w = input.nextLine();
list.add(w);
}
} catch (Exception ex) {
System.out.println("File not found.");
}
}
public String getword() {
if (list.isEmpty()) {
return "NOTHING";
}
return list.get((int) (Math.random() * list.size()));
}
}
public class test {
public static void main(String[] args) {
WordGen wordgen = new WordGen();
System.out.println(wordgen.getword());
}
}
I tried searching for this problem but couldn't find it here. I am guessing it's a very small error which I cannot figure out. Thanks and regards.
EDIT: Here's the other code that worked(Everything else same as before):
public WordGenerator()
{
try(InputStream input = getClass().getResourceAsStream(fileName);
BufferedReader bfreader = new BufferedReader(new InputStreamReader(input)))
{
String line = "";
while ((line = bfreader.readLine()) != null)
words.add(line);
}
catch (Exception e)
{
System.out.println("Couldn't find file");
}
}
Scanner is trying to load a file - and you're providing an absolute filename, /res/words.txt.
In order to create an InputStream, you're loading a resource, giving it an absolute resource name, even though you've called the variable fileName:
getClass().getResourceAsStream(fileName)
That works because it can load a resource called /res/words.txt from the classpath, but it's not loading a file with a filename of /res/words.txt.
You could use a filename of res/words.txt, if you run the code from the src directory... or you could just stick to using getResourceAsStream, which is probably a better idea as it doesn't rely on your working directory, and will continue to work even if your code and resources are packaged up into a jar file.
If you really want to use Scanner, you could always use new Scanner(input) - there's a Scanner constructor accepting an InputStream.
package healthbuddy;
/**
*
* #author tpzap_000
*/
import java.io.*;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.StaxDriver;
import com.thoughtworks.xstream.persistence.FilePersistenceStrategy;
import com.thoughtworks.xstream.persistence.PersistenceStrategy;
import com.thoughtworks.xstream.persistence.XmlArrayList;
import java.util.List;
import java.util.Scanner;
public class PersistentDataModelCntl implements Serializable{
private File theFile = new File("PDM.txt");
private XStream xstream = new XStream(new StaxDriver());
public static PersistentDataModelCntl thePDMCntl;
private PersistentDataModel thePDM;
public PersistentDataModelCntl(){
this.readPDMFile();
}
public static PersistentDataModelCntl getPDMCntl(){
if(thePDMCntl == null){
thePDMCntl = new PersistentDataModelCntl();
}
return thePDMCntl;
}
public void readPDMFile(){
try
{
System.out.println("in read file");
StringBuilder fileContents = new StringBuilder();
Scanner in = new Scanner(theFile);
String tempXML;
boolean test = in.hasNextLine();
System.out.println(test);
while(in.hasNextLine()){
fileContents.append(in.nextLine());
System.out.println("reading file contents");
}
tempXML = fileContents.toString();
thePDM = (PersistentDataModel)xstream.fromXML(tempXML);
}
//If the file does not exist, thePDM is instantiated to be a new, empty, PDM file. The file is then written to disk, and then read from disk
// using some recursive stuff. Also creates a test UserList so that I don't get a NullPointerException in the LoginCntl.
catch(FileNotFoundException ex){
System.out.println("FileNotFound");
thePDM = new PersistentDataModel();
thePDM.thePDMFoodList = new FoodList();
thePDM.thePDMMealList = new MealList();
thePDM.thePDMDietList = new DietList();
thePDM.thePDMDiet = new Diet();
//Creates new attributes if things are null.
this.writePDMFile();
this.readPDMFile();
System.out.println("FileNotFound Exception");
}
catch(IOException ex){
System.out.println("IO Exception");
ex.printStackTrace();
}
}
//Problem Code is here:
public void writePDMFile(){
try{
String xml = xstream.toXML(thePDM);
PrintWriter writer = new PrintWriter(theFile);
System.out.println(xml);
writer.println(xml);
}
catch(Exception ex){
System.out.println("There was a problem writing the file.");
}
}
public PersistentDataModel getPDM(){
return thePDM;
}
}
Above is my code. I currently have an app that uses object serialization for it's data persistence, but I'm in the process of converting it to XML. I'm using the Xstream library to create the XML, but I'm having some trouble writing it to disc. Xstream gives me the XML as a String, which I then attempt to write to a text file using PrintWriter. However the text file is empty, but the String I'm attempting to write to it is not. My understanding of PrintWriter is such that you supply it the file name it should be writing to, it attempts to write to that file(creates it if it does not exist), and then it should write the contents of the String to the file.
Any assistance would be greatly appreciated. Not sure where I'm going wrong.
You need to add
writer.close()
to the end of your code. The writer only writes to file when it is closed.
You need to call PrintWriter::flush() or PrintWriter::close().
Try to close PrintWriter after you wrote xml to file
I'm an idiot. I didn't call close on my PrintWriter.
So lets say I have a txt file that I want to write to with a PrintWriter. How come the following code deletes the old contents of the file everytime its called?
Code:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class Test {
public static void main(String[] args) {
writeToFile("foo");
writeToFile("bar");
}
public static void writeToFile(String text) {
try {
PrintWriter printer = new PrintWriter(new File("myTextFile.txt"));
printer.println("Your text is:" + text);
printer.close();
} catch (FileNotFoundException fnfe) {
fnfe.printStackTrace();
}
}
}
Output:
Your text is:bar
I'm guessing its something to do with the fact that I'm creating a new PrintWriter or a new File every time the method is being called, but having only one instance being created in the main method failed to work as well.
If you want to add to a file's contents, you need to explicitly open the file for append; the default in most languages is overwrite.
To do so in Java, use new FileWriter("myfile.txt", true). You can then wrap a PrintWriter around that if desired.