I have a super beginner's question. I have a computer science test today and one of the practice problems is this:
Write a program that carries out the following tasks:
Open a file with the name hello.txt.
Store the message “Hello, World!” in the file.
Close the file.
Open the same file again.
Read the message into a string variable and print it.
This is the code I have for it so far:
import java.util.*;
import java.io.*;
public class ReadFile
{
public static void main(String[] args) throws FileNotFoundException
{
PrintWriter out = new PrintWriter("hello.txt");
out.println("Hello, World");
File readFile = new File("hello.txt");
Scanner in = new Scanner(readFile);
ArrayList<String> x = new ArrayList<String>();
int y = 0;
while (in.hasNext())
{
x.add(in.next());
y++;
}
if (x.size() == 0)
{
System.out.println("Empty.");
}
else
{
System.out.println(x.get(y));
}
in.close();
out.close();
}
}
What's wrong with this code?
1) You need to close the stream
2) You need to refer to the x Arraylist with (y-1) otherwise you will get
a java.lang.IndexOutOfBoundsException . The indexes starts from 0 and not from 1.
http://www.tutorialspoint.com/java/util/arraylist_get.htm
public static void main(String[] args) throws FileNotFoundException
{
PrintWriter out = new PrintWriter("hello.txt");
out.println("Hello, World");
out.close();
File readFile = new File("hello.txt");
Scanner in = new Scanner(readFile);
ArrayList<String> x = new ArrayList<String>();
int y = 0;
while (in.hasNext())
{
x.add(in.next());
y++;
}
in.close();
if (x.size() == 0)
{
System.out.println("Empty.");
}
else
{
System.out.println(x.get(y-1));
}
}
}
I guess what's wrong with the code ist that you cant read anything from the file.
this is because PrintWriter is buffered
fileName - The name of the file to use as the destination of this writer. If the file exists then it will be truncated to zero size; otherwise, a new file will be created. The output will be written to the file and is buffered.
You need to close the file you have just writen to before openning it for reading so that the changes are fluched to the physical storage. Thus moving out.close(); right after out.println("Hello, World");
class FileWritingDemo {
public static void main(String [] args) {
char[] in = new char[13]; // to store input
int size = 0;
try {
File file = new File("MyFile.txt"); // just an object
FileWriter fw = new FileWriter(file); // create an actual file & a FileWriter obj
fw.write("Hello, World!"); // write characters to the file
fw.flush(); // flush before closing
fw.close(); // close file when done
FileReader fr = new FileReader(file); // create a FileReader object
size = fr.read(in); // read the whole file!
for(char c : in) // print the array
System.out.print(c);
fr.close(); // again, always close
} catch(IOException e) { }
}
}
Related
I'm having an issue with changing a line in a file, the purpose of this code is to change the first number of the file to itself + 1. For some reason the code doesn't seem to be functioning at all, any help would be appreciated!
public static void changenumber(String fileName)
{
ArrayList<String> list = new ArrayList<String>();
File temp = new File(fileName);
Scanner sc;
try {
sc = new Scanner(temp);
while (sc.hasNextLine())
{
list.add(sc.nextLine());
}
sc.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
String first = list.get(0);
int i = Integer.parseInt(first);
i = i+1;
first = Integer.toString(i);
list.set(0, first);
writenumber(list,fileName);
}
public static void writenumber(ArrayList<String> list, String fileName)
{
PrintWriter write;
try {
write = new PrintWriter(new FileWriter(fileName, true));
for(int i = 0; i<list.size();i++)
{
write.append(list.get(i));
}
}
catch(IOException err)
{
err.printStackTrace();
}
}
Your problem is that you never closed the FileWriter.
Use try-with-resources to ensure that file streams are closed correctly.
A few other improvements to your code:
Do not ignore exceptions. Continuing execution as-if nothing bad happened will cause lots of problems. Let the exception bounce back to caller, and let caller decide what to do if the file cannot be updated.
Scanner is slow. Since all you're doing to reading lines, use BufferedReader instead.
The lines in memory don't end in newline characters, so you need to use the println() method when writing the lines back out, otherwise the result is a file with all the lines concatenated into a single line.
Variables renamed to be more descriptive.
public static void changenumber(String fileName) throws IOException {
ArrayList<String> lines = new ArrayList<>();
try (BufferedReader in = new BufferedReader(new FileReader(fileName))) {
for (String line; (line = in.readLine()) != null; ) {
lines.add(line);
}
}
int i = Integer.parseInt(lines.get(0));
i++;
lines.set(0, Integer.toString(i));
writenumber(lines, fileName);
}
public static void writenumber(List<String> lines, String fileName) throws IOException {
try (PrintWriter out = new PrintWriter(new FileWriter(fileName, true))) {
for (String line : lines) {
out.println(line);
}
}
}
Of course, you could simplify the code immensely by using the newer NIO.2 classes added in Java 7, in particular the java.nio.file.Files class.
public static void changenumber(String fileName) throws IOException {
Path filePath = Paths.get(fileName);
List<String> lines = Files.readAllLines(filePath);
lines.set(0, Integer.toString(Integer.parseInt(lines.get(0)) + 1));
Files.write(filePath, lines);
}
I am trying to create a uid generator with java using file writer and reader I want it to generate id with serial 1 then 2 then 3 and so. on. but it isn't working correctly I want to store it in file so that it starts from last ended number when program starts again. This is my code
import java.io.*;
import java.util.*;
import java.text.*;
class java{
static void main()throws IOException{try{
Scanner in=new Scanner(System.in);
String s=null;
File f =new File("C:\\DMCH\\U.IDN");
if(!f.exists()){
f.mkdirs();}
else
System.out.print("");
File file =new File("C:\\DMCH\\U.IDN\\uid.txt");
if(!file.exists()){
file.createNewFile();}
else
System.out.print("");
DateFormat uid=new SimpleDateFormat("dMyy",Locale.US);
s=uid.format(new Date())+"00";
Writer fo=new FileWriter("C:\\DMCH\\U.IDN\\uid.txt");
fo.write(s);
fo.close();
System.out.println(s);
FileInputStream fi =new FileInputStream("C:\\DMCH\\U.IDN\\uid.txt");
BufferedReader br=new BufferedReader(new InputStreamReader(fi));
String st=null,tmp;
while((tmp=br.readLine())!=null){
st=tmp;
}
fi.close();
long i=Long.valueOf(st)+1;
System.out.println("Enter getuid to get uid");
String str=in.next();
if(str.equals("getuid"))
{
System.out.println(i);
}
Writer foo=new FileWriter("C:\\DMCH\\U.IDN\\uid.txt");
foo.write(Long.toString(i));
foo.close();
}catch(NumberFormatException n){}
}
}
I want it to generate uid as:
17051701
then
17051702
and so. on.
and I want it to start from last ended point after restarting the program
for example in the above case program must give next uid as:
17051703.
I think you want this. Another time when you ask the question you should put your code. then others can get better understand what you want.
public static void main( String[] args ) {
try {
int fileReader = fileReader();
System.out.println(fileReader + 1);
fileWrite(fileReader + 1);
} catch ( FileNotFoundException e ) {
e.printStackTrace();
} catch ( IOException e ) {
e.printStackTrace();
}
}
private static int fileReader() throws FileNotFoundException, IOException {
File f = new File("E:\\yourlocation\\MyFile.txt");
String value = "0";
if ( f.exists() ) {
FileReader reader = new FileReader(f);
BufferedReader bufferedReader = new BufferedReader(reader);
String line;
while ( (line = bufferedReader.readLine()) != null ) {
value = line;
}
reader.close();
}
return Integer.parseInt(value);
}
private static void fileWrite( int id ) throws IOException {
FileWriter writer = new FileWriter("E:\\yourlocation\\MyFile.txt", true);
writer.write(id + "");
writer.write("\r\n"); // write new line
writer.close();
}
I have a text file with the following format:
String1
String1String2
String1String2String3
....
String1Strin2String3.....String(i)...String(n)
I want to remove some parts of this file to have the following format(result file):
String1
String2
String3
...
String(i)
String(n)
I tried with this fonction but my output file is always empty:
public static void FileFormatted(String inputFile,String outputFile)
{
String FileContent = readFile(inputFile,
StandardCharsets.UTF_8);
String[] FileSentences = FileContent.split("[\n]");
for (int i = 0; i < FileSentences.length; i++)
{
StringBuilder builder = new StringBuilder();
for(int j=1;j<FileSentences.length;j++)
{
int index= FileSentences[j].indexOf("FileSentences[i]");
String temp=FileSentences[j].substring(index);
FileSentences[j]=FileSentences[j].replaceAll(temp," ");
builder.append(FileSentences[j]+ "\n");
}
writeIntoFile(builder, outputFile, true);
}
}
public static void writeIntoFile(StringBuilder stringBuilder,
String txtFilePath, boolean append) {
File file = new File(txtFilePath);
// if file doesn't exists, then create it
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
FileWriter fw;
try {
fw = new FileWriter(file.getAbsoluteFile(), append);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(stringBuilder.toString());
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Can someone please help me.
Okay, first of all reading the whole file in, in one go is bad practice. Imagine you have a 6gb file, that means you need 6gb of RAM to store that file when you read it in. It would be better to read the file line by line.
So the Aim of the logic would be read line by line.
When we read the first line we can get the length of it.
When we read read the second line we know the length of the first line so that means it is our starting point on the second line. This means you can use sub-string method, passing the start position and end position.
And repeat this logic for line 3,4,...n
The benefit of this is that you don't waste memory, you are only storing the size of the line in text.
Update
I have written the code that I suggested earlier. It's pretty basic and there is no validation so you will need to add to it. But it covers the basics
public static void main(String[] args) throws IOException {
FileReader fileReader = new FileReader("test.txt");
BufferedReader br = new BufferedReader(fileReader);
int startPosition = 0;
String line;
ArrayList<String> items = new ArrayList<String>();
while((line = br.readLine() ) != null)
{
items.add(line.substring(startPosition, line.length()));
System.out.println(line.substring(startPosition, line.length()));
startPosition = line.length();
}
write("test2.txt", items);
}
public static void write (String filename, ArrayList<String> items) throws IOException{
BufferedWriter outputWriter = null;
outputWriter = new BufferedWriter(new FileWriter(filename));
for (String item : items) {
outputWriter.write(item);
outputWriter.newLine();
}
outputWriter.flush();
outputWriter.close();
}
be sure the pattern is consistent in the hole file, then Do this:
public static void main(String[] args) {
String wordTofind = "String";
String st = "String1String2String3String4";
String[] arra = st.split(wordTofind);
for (int i = 1; i < arra.length - 1; i++) {
System.out.println(wordTofind + arra[i]);
//write to a file or similar.
}
}
you can use regex too, but this is acceptable...
I have a bunch of code that has now evolved into a fully functioning console based (mostly) game. I'm now curious that if I want to implement an Input/Output function do I have to create it in a different file or can I put it in the same class as my code. For instance, an example my lecturer has given for writing a fileIO for saving names is the following:
import java.io.*;
class savenames
{
public static void main(String[] params) throws IOException
{
PrintWriter outputStream = new PrintWriter(new FileWriter("mydata.txt"));
// Create an array with some sample names to store
String [] names = {"Paul", "Jo", "Mo"};
// Store the names from the array in the file, one name per line
for (int i = 0; i < names.length; i++)
{
outputStream.println(names[i]);
}
outputStream.close();
System.exit(0);
}
}
This accompanies the following code (in a different file):
import java.io.*;
class readnames
{
public static void main(String[] params) throws IOException
{
BufferedReader inStream = new BufferedReader(new FileReader("mydata.txt"));
String [] names = new String[3];
System.out.println("The names in the file mydata.txt are:");
for (int i = 0; i < names.length; i++)
{
names[i] = inStream.readLine();
System.out.println(names[i]);
}
inStream.close();
System.exit(0);
}
}
I was just wondering if it would be possible do the two things in the same file, as my code has many different methods and I'm not sure how to make a separate method to do this. Thanks.
EDIT: Perhaps I can modify this question to make it a little better.
I have the following main method in my boardgame:
class newminip
{
public static void main (String[] params) throws IOException
{
numberPlayers();
int diceroll = dicethrow(6);
int[] scorep1 = scorearrayp1();
questions(diceroll, scorep1);
sort(scorep1);
System.exit(0);
}
.... insert code here ....
public static void exitmethod(int[] scorep1)
{
sort(scorep1);
for (int i = 0; i < 4; i++)
{
System.out.println("Player " + (i+1) + " scored " + scorep1[i] + "");
}
System.exit(0);
}
} //END class
And I want something that will save the scores into a new text file. I hope this had made it a tiny bit clearer.
Yes you could do it in one file. I have created a new class for it:
import java.io.*;
import java.util.ArrayList;
public class FileIO {
public static String[] readStringsFromFile(final String filename) throws IOException {
BufferedReader inStream = new BufferedReader(new FileReader(filename));
//Use ArrayList since you don't know how many lines there are in the file
ArrayList<String> lines = new ArrayList<String>();
String line;
//Read until you reach the end of the file
while ((line = inStream.readLine()) != null) {
lines.add(line);
}
inStream.close();
//Convert it back to a string array
return lines.toArray(new String[lines.size()]);
}
public static void writeStringsToFile(String[] lines, final String filename) throws IOException {
PrintWriter outputStream = new PrintWriter(new FileWriter(filename));
for (int i = 0; i < lines.length; i++) {
outputStream.println(lines[i]);
}
outputStream.close();
}
public static void main(String[] args) {
//To test the methods:
//Create an array to write to the file
String[] linesToWrite = {"firstLine", "secondLine", "thirdLine"};
try {
//Write the strings to a file named "testfile.txt"
writeStringsToFile(linesToWrite, "testfile.txt");
//Read all lines of a file named "testfile.txt"
String[] readLines = readStringsFromFile("testfile.txt");
//Print out the read lines
for (String line : readLines) {
System.out.println(line);
}
} catch (IOException e) {
System.err.println("Error msg");
}
}
}
The main method in this case is just to test, you can remove it and copy the two other methods to your class. This is probably not the best or most efficient way to do file io but in your case this should do the job (:
EDIT:
So if you just need to read an write integers to a file you could use something like this:
import java.io.*;
import java.util.ArrayList;
public class FileIO {
public static Integer[] readIntegersFromFile(final String filename) throws IOException {
BufferedReader inStream = new BufferedReader(new FileReader(filename));
//Use ArrayList since you don't know how many lines there are in the file
ArrayList<Integer> integers = new ArrayList<Integer>();
String line;
//Read until you reach the end of the file
while ((line = inStream.readLine()) != null) {
//Parse integers form read string values
integers.add(Integer.parseInt(line));
}
inStream.close();
return integers.toArray(new Integer[integers.size()]);
}
public static void writeIntegersToFile(Integer[] lines, final String filename) throws IOException {
PrintWriter outputStream = new PrintWriter(new FileWriter(filename));
for (int i = 0; i < lines.length; i++) {
outputStream.println(lines[i]);
}
outputStream.close();
}
public static void main(String[] args) {
//To test the methods:
//Create an array to write to the file
Integer[] linesToWrite = {1, 100, 15};
try {
//Write the strings to a file named "testfile.txt"
writeStringsToFile(linesToWrite, "testfile.txt");
//Read all lines of a file named "testfile.txt"
Integer[] readLines = readStringsFromFile("testfile.txt");
//Print out the read lines
for (int line : readLines) {
System.out.println(line);
}
} catch (IOException e) {
System.err.println("Error msg");
}
}
}
You can create a Java file with the code from both main methods and remove the System.exit(0); as you don't need it. This way one program will do both. I suggest you write the file before attempting to read it.
Putting it all in one program make the use of the file rather redundant however, in which case you can just print the array.
This is what I have to do:
Create a new copy of the TestFileWriter program called WriterDemo that takes input from the user and writes it into the output file. The program should continue writing lines (a loop may help) until the user supplies an empty line (no text) as their input. Hint: a while loop that has a termination condition that depends on the input string from the user is a good place to start...
The program should be accessed from the terminal and I can't figure out where to put the while loop without ruining the program. The code below is the unmodified version of TestFileWriter. I don't need the full code of WriterDemo, but just some advice on how to use it. An help is greatly appreciated.
import java.io.FileReader;
import java.io.FileWriter;
public class WriterDemo {
public static void main(String args[]){;
FileWriter fout;
FileReader fin;
String str;
int k;
if(args.length==0){
System.out.println("Use an argument in the command line");
System.exit(0);
}
try{
fout = new FileWriter("WrittingProbe.txt");
for(int i=0; i<args.length; i++){
fout.write(args[i]);
fout.write(' ');
}
fout.close();
fin= new FileReader("WrittingProbe.txt");
System.out.println("The file content is:");
while((k=fin.read()) !=-1)
System.out.println((char)k);
System.out.println();
fin.close();
fout = new FileWriter("WrittingProbe.txt", true);
str="\nAdded Text\n";
fout.write(str);
fout.close();
fin = new FileReader("WrittingProbe.txt");
System.out.println("\nNow the file content is:");
while((k=fin.read()) != -1)
System.out.print((char)k);
System.out.println();
fin.close();
}
catch(Exception e){
System.out.println("Exception: " + e);
}
}
}
try (FileWriter fileWriter = new FileWriter("G:\\test.txt")) {
Scanner scn = new Scanner(System.in);
while (true) {
String string = scn.nextLine();
if (string.equals("0")) {
break;
} else {
fileWriter.write(string+"\n");
}
}
}
Scanner scn = new Scanner(System.in);
ArrayList<String> list = new ArrayList<String>();
list.add(scn.nextLine());
for(;!list.get(list.size()-1).equals("");){ //Loops until the last input is a blank line
list.add(scn.nextLine());
//Or, you can do it here, as you go, if you want
}
//Or here, all at once, using the list