I'm making a program where I store a songs' title, artist, and genre into into a data file. Like this:
public void writeSong(Song t) throws IOException {
File myFile = new File(Song.getFileInput());
RandomAccessFile write = new RandomAccessFile(myFile,"rw");
write.writeChars(title);
write.writeChars(artist);
write.writeChars(genre);
write.close();
}
After I do that, I'm supposed to read the data file and display the contents of it like this:
public Song readSong() throws FileNotFoundException, IOException {
File myFile = new File(Song.getFileInput());
RandomAccessFile read = new RandomAccessFile(myFile, "rw");
String readTitle = null, readArtist = null, readGenre = null;
Song so = null;
read.seek(0);
for(int i = 0; i < title.length(); i++){
readTitle += read.readChar();
}
read.seek(50);
for(int i = 0; i < artist.length(); i++){
readArtist += read.readChar();
}
read.seek(100);
for(int i = 0; i < genre.length(); i++){
readGenre += read.readChar();
}
so = new Song(readTitle, readArtist, readGenre);
read.close();
return so;
}
If I assign it to a file called "songs.dat", it's supposed to write and read the songs off that file. After I exit the program and run it again, I make the file called "songs.dat" again. But when I want to read and display the songs, nothing happens. Does anyone how to resolve this problem?
RandomAccessFile.seek(long position) set the file position where you want to read or write.
When you begin to read your file you set the position to 0 with read.seek(0). But from there you dont need to reset it :
public Song readSong() throws FileNotFoundException, IOException {
File myFile = new File(Song.getFileInput());
RandomAccessFile read = new RandomAccessFile(myFile, "rw");
String readTitle = "", readArtist = "", readGenre = "";
Song so = null;
read.seek(0);
for(int i = 0; i < title.length(); i++){
readTitle += read.readChar();
}
for(int i = 0; i < artist.length(); i++){
readArtist += read.readChar();
}
for(int i = 0; i < genre.length(); i++){
readGenre += read.readChar();
}
so = new Song(readTitle, readArtist, readGenre);
read.close();
return so;
}
I also initialize your String to empty String so you dont have "null" string in the first place as a result
Related
I have 6 columns in one table and one of the column contains Chinese character and I have 200 records in that table.
I have written the code to save it one text file. The problem is while fetching all records, I am able to see the chinese text in the file. But while fetching only one record I am seeing the Chinese text is garbled.
I am using the below code.
public static void main(String args[]){
String outputFile = fileNameEncode("C:\\a\a.txt");
FileOutputStream os = new FileOutputStream(outputFile);
writeToFile(os);
}
private static String fileNameEncode(String name) {
String file;
try {
byte[] utf_byte = name.getBytes("UTF-8");
StringBuilder sb = new StringBuilder(1024);
for (byte b : utf_byte) {
int integer = b & 0xFF; // drop the minus sign
sb.append((char) integer);
}
file = sb.toString();
} catch (Exception e) {
file = name;
}
return file;
}
public void writeToFile(FileOutputStream os) {
PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(ostream, "GBK")));
for (int rowNum = 0; rowNum < arrayList.size(); rowNum++) {//arrayList contains data from db
ArrayList list = arrayList.get(rowNum);
for(int k = 0; k < list.size(); k++{
String[] data = new String[6];
for (int colNum = 0; colNum < 6; colNum++) {
data[colNum] = list.get(i).toString();
}
String outLine = composeLine(data, ctlInfo);
// write the line
pw.print(outLine);
pw.println();
}
}
}
private static String composeLine(String[] data, ControlInfo ctl) {
StringBuilder line = new StringBuilder();
String delim = ","
int elemCount = data.length;
for (int i = 0; i < elemCount; i++) {
if (i > 0)
line.append(delim);
if (data[i] != null && (data[i].contains("\n") || data[i].contains("\r") ||
data[i].contains("\r\n"))){
data[i] = data[i].replaceAll("(\\t|\\r?\\n)+", " ");
}
else {
line.append(data[i]);
}
}
return line.toString();
}
could you please let me know where I am wrong?
I found the issue, the code is good, the problem is in notepad++. If the character set in node pad ++ is Chinese(GB2312) then I am able to see the correct text. The note pad ++ is auto set GB2312 for two lines but for one line it is not doing auto set to GB2312.
When I convert my Java project into a Jar file, an ArrayIndexOutOfBounds exception of -2 occurs in line 3 of this section of code:
for (int i = 0; i < copy.get(copy.size() - 2).size(); i++) {
if (!copy.get(copy.size() - 2).get(i).toString().equals(" ")) {
startLocations[index] = Integer.parseInt(copy.get(copy.size() - 2).get(i).toString());
index++;
}
}
I find this very strange because the program runs perfectly fine in Eclipse, and the size of copy, a 2D ArrayList tempoarily holding the grid of a maze is 9. The code fails when I convert it to a Jar and I run it from cmd. Here is the full relevant code below. All the files are in their correct locations.
String fileName = "maze.txt";
String line = null;
ArrayList < ArrayList < Square >> grid = new ArrayList < ArrayList < Square >> ();
try {
// Setup FileReader, BufferedReader, and LineReader
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader);
int row = 0;
// Get all the lines inside the maze file
while ((line = bufferedReader.readLine()) != null) {
ArrayList < Square > lineList = new ArrayList < Square > ();
for (int i = 0; i < line.length(); i++) {
String letter = Character.toString(line.charAt(i));
if (letter.equals("L")) {
lineList.add(new LockedSquare(row, i, letter));
} else {
lineList.add(new Square(row, i, letter));
}
row++;
}
grid.add(lineList);
}
// Cut down grid to only the maze
ArrayList < ArrayList < Square >> copy = grid;
int length = grid.size();
grid = new ArrayList < ArrayList < Square >> ();
for (int i = 0; i < length - 2; i++) {
grid.add(copy.get(i));
}
// Start position
int[] startLocations = new int[2];
int index = 0;
for (int i = 0; i < copy.get(copy.size() - 2).size(); i++) {
if (!copy.get(copy.size() - 2).get(i).toString().equals(" ")) {
startLocations[index] = Integer.parseInt(copy.get(copy.size() - 2).get(i).toString());
index++;
}
}
int playerX = startLocations[0];
int playerY = startLocations[1];
}
// Exceptions
catch (FileNotFoundException e) {
System.out.println("Error: maze.txt not found");
} catch (IOException ex) {
System.out.println("Error reading maze.txt");
}
This is happening because your jar file is unable to find maze.txt .
change String fileName = "maze.txt";
to
String fileName = <absolute-path-for-maze.txt> ; and it should be through in jar
Woops. I was so stupid. My maze.txt file in the same folder as my JAR has no content in it.
Sorry for click bait title, but it is my problem, and I can't really change to wording without losing the question.
I have the following code which is meant to select a file, read it, and find it's mode, and I think I got it done, but I have one issue
public class ModeFinder
{
public static int countDoubles(File file) throws FileNotFoundException
{
Scanner reader = new Scanner(file);
int count = 0;
while (reader.hasNextDouble())
{
count++;
reader.nextDouble();
}
reader.close();
return count;
}
public static void main(String args[]) throws FileNotFoundException
{
String filename;
FileDialog filePicker = new FileDialog(new JFrame());
filePicker.setVisible(true);
filename = filePicker.getFile();
String folderName = filePicker.getDirectory();
filename = folderName + filename;
System.out.println("filename = " +filename);
File inputFile = new File(filename);
Scanner fileReader = new Scanner (inputFile);
int maxValue = 0,
maxCount = 0;
int[] a = new int[countDoubles(inputFile)];
while (fileReader.hasNextInt())
{
for (int i = 0; i < a.length; i++)
{
int count = 0;
for (int j = 0; j < a.length; j++)
{
if (a[j] == a[i])
count++;
}
if (count > maxCount)
{
maxCount = count;
maxValue = a[i];
}
}
}
System.out.println("The most common grade is: " +maxValue);
}
}
The last bit with the most common grade doesn't even print and I don't know why.
You aren't calling nextInt to get the value from the file so your while loop is going to loop forever. You need something like:
while (fileReader.hasNextInt())
{
int value = fileReader.nextInt();
...
I am beginner of Java.
I am trying to read two files and then get the union of them. I should use an array with size 100. (only one array allowed)
First, I read all records from file1, and write them to the output, file3. For that purpose, I read 100 records at a time, and write them to file3 using iteration.
After that, like file1, this time I read second file as 100 records at a time, and write them to the array, memory[]. Then I find the common records, if the record which I read from file2 is not in file1, I write it to the output file. I do this until reader2.readLine() gets null and I re-open file1 in each iteration.
This is what I have done so far, almost done, but it gives NullPointerException. Any help would be appreciated.
Edit: ok, now it doesn't give any exception, but it doesn't find the different records and can't write them. I guess the last for loop and booleans don't work , why? please help...
import java.io.*;
public class FileUnion
{
private static long startTime, endTime;
public static void main(String[] args) throws IOException
{
System.out.println("PROCESSING...");
reset();
startTimer();
String[] memory = new String[100];
int memorySize = memory.length;
File file1 = new File("stdlist1.txt");
BufferedReader reader1 = new BufferedReader(new FileReader(file1));
File file3 = new File("union.txt");
BufferedWriter writer = new BufferedWriter(new FileWriter(file3));
int numberOfLinesFile1 = 0;
String line1 = null;
String line11 = null;
while((line1 = reader1.readLine()) != null)
{
for (int i = 0; i < memorySize; )
{
memory[i] = line1;
i++;
if(i < memorySize)
{
line1 = reader1.readLine();
}
}
for (int i = 0; i < memorySize; i++)
{
writer.write(memory[i]);
writer.newLine();
numberOfLinesFile1++;
}
}
reader1.close();
File file2 = new File("stdlist2.txt");
BufferedReader reader2 = new BufferedReader(new FileReader(file2));
String line2 = null;
while((line2 = reader2.readLine()) != null)
{
for (int i = 0; i < memorySize; )
{
memory[i] = line2;
i++;
if(i < memorySize)
{
line2 = reader2.readLine();
}
}
for (int k = 0; k < memorySize; k++ )
{
boolean found = false;
File f1 = new File("stdlist1.txt");
BufferedReader buff1 = new BufferedReader(new FileReader(f1));
for (int m = 0; m < numberOfLinesFile1; m++)
{
line11 = buff1.readLine();
if (line11.equals(memory[k]) && found == false);
{
found = true;
}
}
buff1.close();
if (found == false)
{
writer.write(memory[k]);
writer.newLine();
}
}
}
reader2.close();
writer.close();
endTimer();
long time = duration();
System.out.println("PROCESS COMPLETED SUCCESSFULLY");
System.out.println("Duration: " + time + " ms");
}
public static void startTimer()
{
startTime = System.currentTimeMillis();
}
public static void endTimer()
{
endTime = System.currentTimeMillis();
}
public static long duration()
{
return endTime - startTime;
}
public static void reset()
{
startTime = 0;
endTime = 0;
}
}
memory[k] is null. Why is this null? Because in this code:
while((line2 = reader2.readLine()) != null)
{
for (int i = 0; i < 100; i++)
{
memory[i] = line1;
i++;
if(i < 100)
{
line2 = reader2.readLine();
}
}
you say memory[i] = line1;
line1 however is always null because you used it before in a loop which ended when line1 is null.
I believe you intended to write **memory[i] = line2;** in the above code :)
You have to check that you've not yet reached the end of the file. In all loops where you have a lineX = readerX.readLine(), immediately check whether lineX == null and break out of the loop if it is.
Edit my own answer because code doesn't show well in comments.
while(!line11.equals(memory[k]))
{
line11 = buff1.readLine();
}
It's line11 that is (sometimes) null here. If memory[k] is not in file1, what happens?
I am beginner with Java.
This is my approach:
I am trying to read two files and then get the union of them. I should am using an array with size 100. (just one array allowed, reading and writing line by line or arrayList or other structures are not allowed.)
First, I read all records from file1, and write them to the output, a third file. For that purpose, I read 100 record at a time, and write them to the third file using iteration.
After that, like first file, this time I read second file as 100 records at a time, and write them to the memory[]. Then I find the common records, if the record which I read from File2 is not in File1, I write it to the output file. I do this until reader2.readLine() gets null and I re-open file1 in each iteration.
This is what I have done so far, almost done. Any help would be appreciated.
Edit: ok, now it doesn't give any exception, but it can't find the different records and can't write them. I guess the last for loop and booleans don't work , why? I really need help. Thanks for your patience.
import java.io.*;
public class FileUnion
{
private static long startTime, endTime;
public static void main(String[] args) throws IOException
{
System.out.println("PROCESSING...");
reset();
startTimer();
String[] memory = new String[100];
int memorySize = memory.length;
File file1 = new File("stdlist1.txt");
BufferedReader reader1 = new BufferedReader(new FileReader(file1));
File file3 = new File("union.txt");
BufferedWriter writer = new BufferedWriter(new FileWriter(file3));
int numberOfLinesFile1 = 0;
String line1 = null;
String line11 = null;
while((line1 = reader1.readLine()) != null)
{
for (int i = 0; i < memorySize; )
{
memory[i] = line1;
i++;
if(i < memorySize)
{
line1 = reader1.readLine();
}
}
for (int i = 0; i < memorySize; i++)
{
writer.write(memory[i]);
writer.newLine();
numberOfLinesFile1++;
}
}
reader1.close();
File file2 = new File("stdlist2.txt");
BufferedReader reader2 = new BufferedReader(new FileReader(file2));
String line2 = null;
while((line2 = reader2.readLine()) != null)
{
for (int i = 0; i < memorySize; )
{
memory[i] = line2;
i++;
if(i < memorySize)
{
line2 = reader2.readLine();
}
}
for (int k = 0; k < memorySize; k++ )
{
boolean found = false;
File f1 = new File("stdlist1.txt");
BufferedReader buff1 = new BufferedReader(new FileReader(f1));
for (int m = 0; m < numberOfLinesFile1; m++)
{
line11 = buff1.readLine();
if (line11.equals(memory[k]) && found == false);
{
found = true;
}
}
buff1.close();
if (found == false)
{
writer.write(memory[k]);
writer.newLine();
}
}
}
reader2.close();
writer.close();
endTimer();
long time = duration();
System.out.println("PROCESS COMPLETED SUCCESSFULLY");
System.out.println("Duration: " + time + " ms");
}
public static void startTimer()
{
startTime = System.currentTimeMillis();
}
public static void endTimer()
{
endTime = System.currentTimeMillis();
}
public static long duration()
{
return endTime - startTime;
}
public static void reset()
{
startTime = 0;
endTime = 0;
}
}
EDIT! Redo.
Ok, so to use 100 lines at a time you need to check for null, otherwise trying to write null to a file could cause errors.
You are checking if the file is at the end once, and then gathering 99 more peices of info without checking for null.
What if when this line is called:
while((line2 = reader2.readLine()) != null)
there is only 1 line left in the file? Then your memory array contains 99 instances of null, and you try to write null to the file 99 times. That's worse case scenario.
I don't really know how much help we are supposed to give to people looking for homework help, on most sites I'm familiar with it's not even allowed.
here is an example of one way to write the first file.
String line1 = reader1.readLine();
boolean end_of_file1 = false;
while(!end_of_file)
{
for (int i = 0; i < memorySize)
{
memory[i] = line1;
i++;
if(i < memorySize)
{
if((line1 = reader1.readLine()) == null)
{
end_of_file1 = true;
}
}
}
for (int i = 0; i < memorySize; i++)
{
if(!memory[i] == null)
{
writer.write(memory[i]);
writer.newLine();
numberOfLinesFile1++;
}
}
}
reader1.close();
once you have that, to make the checking for copies easier, make a public static boolean that checks the file for it, then you can call that, it will make the code cleaner.
public static boolean isUsed(String f1, String item, int dist)
{
BufferedReader buff1 = new BufferedReader(new FileReader(f1));
for(int i = 0;i<dist;i++)
{
String line = buff1.readLine()
if(line == null){
return false;
}
if(line.equals(item))
{
return true;
}
}
return false;
}
Then use the same method as writing file 1, only before writing each line check to see if !isUsed()
boolean end_of_file2 = false;
memory = new String[memorySize];// Reset the memory, erase old data from file1
int numberOfLinesFile2=0;
String line2 = reader2.readLine();
while(!end_of_file2)
{
for (int i = 0; i < memorySize; )
{
memory[i] = line2;
i++;
if(i < memorySize)
{
if((line2 = reader2.readLine()) == null)
{
end_of_file2 = true;
}
}
}
for (int i = 0; i < memorySize; i++)
{
if(!memory[i] == null)
{
//Check is current item was used in file 1.
if(!isUsed(file1, memory[i], numberOfLinesFile1)){//If not used already
writer.write(memory[i]);
writer.newLine();
numberOfLinesFile2++;
}
}
}
}
reader2.close();
writer.close();
Hope this helps. Notice I'm not supplying the full code, because I've learned that just pasting the code will make it more likely for copy and paste to just use a code without understanding it. I hope you find it useful.