Changing the first line in a file - java

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);
}

Related

how to remove a line of file from an other line in the same file?

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...

Is it possible to create fileIO within a program?

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.

How do I remove all occurrences of "," and "[" from the output in java?

Here is my code. The input consists of names of anime(japanese cartoons) which i have stored it in testfile in anime.txt and I am arranging them in alphabetical order and writing it back into another file name animeout.txt.
The input file does not contain any comma or square bracket but the output file has it.
public class Main {
public static ArrayList<String> read(String filePath) throws IOException {
ArrayList<String> names = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new FileReader(filePath));
int numRead = 0;
String line;
while ((line = reader.readLine()) != null) {
names.add(line + "\n");
numRead++;
}
System.out.println("\n\n count " +numRead);
reader.close();
System.out.println(names);
return names;
}
public static void write(ArrayList<String> input) throws IOException
{
File file = new File("Animeout.txt");
file.createNewFile();
FileWriter writer = new FileWriter(file);
writer.write(input);
writer.flush();
writer.close();
}
public static void main(String args[]) throws IOException
{
ArrayList<String> names2 = new ArrayList<String>();
String path= "anime.txt";
String test;
names2 = read(path);
Collections.sort(names2, null);
// System.out.println(names2);
write(names2);
}
}
Input file has about 200 lines. Below is just a small example
One piece
Naruto/naruto shippuden
Bleach
Fullmetal alchemist brotherhood
Fate/stay night
Fairy tale
Blue exorcist
Soul eater
Death note
Output file contains , and [
count 105
[11 eyes
, A certain magical index
, A certain magical index II
, Aldnoah.Zero
, Angel beats!
, Another
, Asu no yoichi
, Bay blade
, Beelzebub
, Ben-To
String str = "[12,34,45]";
String out = str.replaceAll(",|\\[|\\]","");
output:
123445
Why are you using a ObjectOuputStream? That is intended for when you want to serialise Java objects and restore them later. I don't see why you need it here.
Just use a FileWriter, like so:
public static void write(ArrayList<String> input) throws IOException
{
try
{
File file = new File("Animeout.txt");
FileWriter fw = new FileWriter(file);
for (int i = 0; i < input.size(); i++) {
fw.append(input.get(i) + "\n");
}
}
finally
{
try {
if (fw != null)
fw.close();
}
catch (Exception e) {
// ignore
}
}
}
Your write method is unfortunate. Try something like this instead (and remove the + "\n" when reading the lines):
public static void write(ArrayList<String> lines) throws IOException
{
File file = new File("Animeout.txt");
PrintStream ps = null;
try {
ps = new PrintStream(file);
for (final String line : lines) {
ps.println(line);
}
} finally {
if (ps != null) { ps.close(); }
}
}
The ObjectOutputStream you are using is not appropriate for simply writing lines of text.
Finally, if all you want to do is sorting the lines of a text file, at least on a POSIX system, you can just do it with
$ sort anime.txt > Animeout.txt
from the command line.

Code for reading from a text file doesn't work

I am new to Java and it has all been self-taught. I enjoy working with the code and it is just a hobby, so, I don't have any formal education on the topic.
I am at the point now where I am learning to read from a text file. The code that I have been given isn't correct. It works when I hardcode the exact number of lines but if I use a "for" loop to sense how many lines, it doesn't work.
I have altered it a bit from what I was given. Here is where I am now:
This is my main class
package textfiles;
import java.io.IOException;
public class FileData {
public static void main(String[] args) throws IOException {
String file_name = "C:/Users/Desktop/test.txt";
ReadFile file = new ReadFile(file_name);
String[] aryLines = file.OpenFile();
int nLines = file.readLines();
int i = 0;
for (i = 0; i < nLines; i++) {
System.out.println(aryLines[i]);
}
}
}
This is my class that will read the text file and sense the number of lines
package textfiles;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadFile {
private String path;
public ReadFile(String file_path) {
path = file_path;
}
int readLines() throws IOException {
FileReader file_to_read = new FileReader(path);
BufferedReader bf = new BufferedReader(file_to_read);
int numberOfLines = 0;
String aLine;
while ((aLine = bf.readLine()) != null) {
numberOfLines++;
}
bf.close();
return numberOfLines;
}
public String[] OpenFile() throws IOException {
FileReader fr = new FileReader(path);
BufferedReader textReader = new BufferedReader(fr);
int numberOfLines = 0;
String[] textData = new String[numberOfLines];
int i;
for (i = 0; i < numberOfLines; i++) {
textData[i] = textReader.readLine();
}
textReader.close();
return textData;
}
}
Please, keep in mind that I am self-taught; I may not indent correctly or I may make simple mistakes but don't be rude. Can someone look this over and see why it is not sensing the number of lines (int numberOfLines) and why it won't work unless I hardcode the number of lines in the readLines() method.
The problem is, you set the number of lines to read as zero with int numberOfLines = 0;
I'd rather suggest to use a list for the lines, and then convert it to an array.
public String[] OpenFile() throws IOException {
FileReader fr = new FileReader(path);
BufferedReader textReader = new BufferedReader(fr);
//int numberOfLines = 0; //this is not needed
List<String> textData = new ArrayList<String>(); //we don't know how many lines are there going to be in the file
//this part should work akin to the readLines part
String aLine;
while ((aLine = bf.readLine()) != null) {
textData.add(aLine); //add the line to the list
}
textReader.close();
return textData.toArray(new String[textData.size()]); //convert it to an array, and return
}
}
int numberOfLines = 0;
String[] textData = new String[numberOfLines];
textData is an empty array. The following for loop wont do anything.
Note also that this is not the best way to read a file line by line. Here is a proper example on how to get the lines from a text file:
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
ArrayList<String> list = new ArrayList<String>();
while ((line = br.readLine()) != null) {
list.add(line);
}
br.close();
I also suggest that you read tutorials on object oriented concepts.
This is a class that I wrote awhile back that I think you may find helpful.
public class FileIO {
static public String getContents(File aFile) {
StringBuilder contents = new StringBuilder();
try {
//use buffering, reading one line at a time
//FileReader always assumes default encoding is OK!
BufferedReader input = new BufferedReader(new FileReader(aFile));
try {
String line = null; //not declared within while loop
/*
* readLine is a bit quirky :
* it returns the content of a line MINUS the newline.
* it returns null only for the END of the stream.
* it returns an empty String if two newlines appear in a row.
*/
while ((line = input.readLine()) != null) {
contents.append(line);
contents.append(System.getProperty("line.separator"));
}
} finally {
input.close();
}
} catch (IOException ex) {
}
return contents.toString();
}
static public File OpenFile()
{
return (FileIO.FileDialog("Open"));
}
static private File FileDialog(String buttonText)
{
String defaultDirectory = System.getProperty("user.dir");
final JFileChooser jfc = new JFileChooser(defaultDirectory);
jfc.setMultiSelectionEnabled(false);
jfc.setApproveButtonText(buttonText);
if (jfc.showOpenDialog(jfc) != JFileChooser.APPROVE_OPTION)
{
return (null);
}
File file = jfc.getSelectedFile();
return (file);
}
}
It is used:
File file = FileIO.OpenFile();
It is designed specifically for reading in files and nothing else, so can hopefully be a useful example to look at in your learning.

Java file read problem

I have a java problem. I am trying to read a txt file which has a variable number of integers per line, and for each line I need to sum every second integer! I am using scanner to read integers, but can't work out when a line is done. Can anyone help pls?
have a look at the BufferedReader class for reading a textfile and at the StringTokenizer class for splitting each line into strings.
String input;
BufferedReader br = new BufferedReader(new FileReader("foo.txt"));
while ((input = br.readLine()) != null) {
input = input.trim();
StringTokenizer str = new StringTokenizer(input);
String text = str.nextToken(); //get your integers from this string
}
If I were you, I'd probably use FileUtils class from Apache Commons IO. The method readLines(File file) returns a List of Strings, one for each line. Then you can simply handle one line at a time.
Something like this:
File file = new File("test.txt");
List<String> lines = FileUtils.readLines(file);
for (String line : lines) {
// handle one line
}
(Unfortunately Commons IO doesn't support generics, so the there would be an unchecked assignment warning when assigning to List<String>. To remedy that use either #SuppressWarnings, or just an untyped List and casting to Strings.)
This is, perhaps, an example of a situation where one can apply "know and use the libraries" and skip writing some lower-level boilerplate code altogether.
or scrape from commons the essentials to both learn good technique and skip the jar:
import java.io.*;
import java.util.*;
class Test
{
public static void main(final String[] args)
{
File file = new File("Test.java");
BufferedReader buffreader = null;
String line = "";
ArrayList<String> list = new ArrayList<String>();
try
{
buffreader = new BufferedReader( new FileReader(file) );
line = buffreader.readLine();
while (line != null)
{
line = buffreader.readLine();
//do something with line or:
list.add(line);
}
} catch (IOException ioe)
{
// ignore
} finally
{
try
{
if (buffreader != null)
{
buffreader.close();
}
} catch (IOException ioe)
{
// ignore
}
}
//do something with list
for (String text : list)
{
// handle one line
System.out.println(text);
}
}
}
This is the solution that I would use.
import java.util.ArrayList;
import java.util.Scanner;
public class Solution1 {
public static void main(String[] args) throws IOException{
String nameFile;
File file;
Scanner keyboard = new Scanner(System.in);
int total = 0;
System.out.println("What is the name of the file");
nameFile = keyboard.nextLine();
file = new File(nameFile);
if(!file.exists()){
System.out.println("File does not exit");
System.exit(0);
}
Scanner reader = new Scanner(file);
while(reader.hasNext()){
String fileData = reader.nextLine();
for(int i = 0; i < fileData.length(); i++){
if(Character.isDigit(fileData.charAt(i))){
total = total + Integer.parseInt(fileData.charAt(i)+"");
}
}
System.out.println(total + " \n");
}
}
}

Categories

Resources