I am trying to work with file stream and i have a problem.
This is my code :
import java.io.*;
import java.util.*;
public class FileIO {
public static void main(String[] args) {
FileOperations myFile = new FileOperations("C:\\My_Programs\\eclipse\\MyJavaFiles\\myFile.txt");
}
private static class FileOperations {
String fileName;
// constructor without argument
FileOperations() {
fileName = "default";
}
/*
* constructor with argument
* argument is assinged into fileName
* fileName is used to open stream for input and output
*/
FileOperations(String argfileName) {
fileName = argfileName;
try {
// open ouput stream
PrintWriter fileOutput = new PrintWriter(new FileOutputStream(fileName));
// open input stream
BufferedReader fileInput = new BufferedReader(new FileReader(fileName));
} catch (IOException v) {
System.out.println(v);
}
}
}
}
My problem is, that if i implement whole FileOperations class in main method, it works fine and i can use fileOutput and fileInput without any problem.
But i wanted to implement those streams in other method and this is where i got stucked.
Why can't i use something like String fileLine = myFile.fileInput.readLine(); in main method? For me, it looks like those streams are not even opened despite they should be.
I am aware that i didn't close fileInput nor fileOuptu, i would close it after working with file.
Thank you for all advices and explanations!
Related
I'm new to java and I'm having a little problem with my code. There's no error and such, it just keeps saying process finished but no output was displayed. The filename is correct as I've checked.
import java.nio.file.;
import java.io.;
public class GuessingGame {
public GuessingGame() {
String filename = "C:\\Users\\angela\\Documents\\words.txt";
Path path = Paths.get(filename.toString());
try {
InputStream input = Files.newInputStream(path);
BufferedReader read = new BufferedReader(new InputStreamReader(input));
String word = null;
while((word = read.readLine()) !=null) {
System.out.println(word);
}
}
catch(IOException ex) {
}
}
public static void main (String[] args) {
new GuessingGame();
}
}
You are ignoring the exception and you don't close the file. Save some typing by using the built-in input.transferTo() for copying the file to System.out, and pass on the exception for the caller to handle by adding throws IOException to constructor and main.
Replace your try-catch block with this try-with-resources, which handles closing the file after use:
try (InputStream input = Files.newInputStream(path)) {
input.transferTo(System.out) ;
}
You managed to call the intended class, but you also needed to specify the specific function which you have declared in the function. Like so:
public static void main (String[] args) { GuessingGame gg = new GuessingGame; gg.GuessingGame(); }
I´m trying to read from a file teste.txt but I only got FileNotFoundException.
(file teste.txt is located on c:\Java\teste.txt)
Here is a snippet of the code:
public class principal {
public static void main(String args[]) {
String test;
BufferedReader in = FileIO.getReader("c:\\Java\\teste.txt");
test = FileIO.getLine(in);
System.out.println(test);
}
}
public class FileIO {
public static BufferedReader getReader(String name) {
BufferedReader in = null;
try {
File file = new File (name);
String filePath = file.getAbsolutePath();
in = new BufferedReader(new FileReader(filePath));
}
catch (FileNotFoundException e) {
System.out.println("Arquivo não encontrado");
System.exit(0);
}
return in;
}
}
Could anybody help me...
Thanks
In order to debug this, you can use a utility method called
Path path = Paths.get("does-not-exist.txt");
boolean val = Files.exists(path);
You can use built-in methods of the java.nio.file package, instead of doing that BufferedReader thing you are doing.
I made this homework exercise to read text from a text file and store it reversed into another new file. This is the code:
import java.util.*;
import java.io.*;
public class FileEcho {
File file;
Scanner scanner;
String filename = "words.txt";
File file1 ;
PrintWriter pw ;
void echo() {
try {
String line;
file = new File( filename);
scanner = new Scanner( file );
file1 = new File("brabuhr.txt");
pw = new PrintWriter(file1);
while (scanner.hasNextLine()) {
line = scanner.nextLine();
String s = new StringBuilder(line).reverse().toString();
pw.println(s);
}
scanner.close();
} catch(FileNotFoundException e) {
System.out.println( "Could not find or open file <"+filename+">\n"+e
);
}
}
public static void main(String[] args) {
new FileEcho().echo();
}
}
and here is a picture Picture here
The question is: why is the newly generated file decreased in size despite having the same characters but reversed?
Would be great if someone can explain it because even my professor didn't know why is that.
P.S; the context of the file is just some words from the dictionary.
Also in other students computers so the problem is not from my computer
The problem is that you never closed the output stream pw, so that any pending output isn't written to the underlying file. This may cause truncation of your file.
You should have closed the output stream with pw.close() in a finally, or in a try with resources.
try (pw = new PrintWriter(file1)) {
while (scanner.hasNextLine()) {
line = scanner.nextLine();
String s = new StringBuilder(line).reverse().toString();
pw.println(s);
}
}
Your implementation can be simplified to be the following:
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
public class FileEcho {
void echo() throws IOException {
try (PrintWriter pw = new PrintWriter("brabuhr.txt")) {
Files.lines(Paths.get("words.txt"))
.map(s -> new StringBuilder(s).reverse().toString())
.forEach(pw::println);
}
}
public static void main(String[] args) throws IOException {
new FileEcho().echo();
}
}
In this example I used a 'try-with-resources' to have the PrintWriter pw autoclosed.
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.