2014-04-08 6 views
1

답을 찾기가 어려울 정도로 간단한 질문입니다. D. 여기 내 코드 (메신저 스페인어 부분을 번역하려고하는 것) :자바 경로 Files.copy 이름이 존재하는 경우

File carpetanueva = new File("C:"+File.separator+"sistema" + File.separator + 
    fechasal+File.separator+doc); 
carpetanueva.mkdirs();  
carpetanueva.setWritable(true); 
rutadestino = ("c:"+File.separator+"sistema" + 
    File.separator + fechasal+File.separator + 
    doc+File.separator+"imagen.jpg"); 

//realizo la copia de la imagen desde el jfilechooser a su destino: 
Path desde = Paths.get(rutaorigen); 
Path hacia = Paths.get(rutadestino); 

try { 
    Files.copy(desde, hacia); 
    JOptionPane.showMessageDialog(null, 
      "Se adjunto la planilla de ambulancia correctamente");   
} catch (IOException e) { 
    JOptionPane.showMessageDialog(null, "error: "+e.getLocalizedMessage()); 
} 

내가 JFileChooser를에서 "rutaorigen"(frompath)을 얻는다. 그리고 나는 몇몇 변수를 사용하여 "rutadestino"(topath)를 만들었습니다. 그래서이 방법으로 주문할 수 있습니다. 문제는 .. 디렉토리와 파일 "imagen.jpg"가 이미 존재하면 오류가 발생합니다. (예외) .. 이미 이미지가 있는지 확인하고 이미지가 있으면 새 이미지의 이름을 바꾸려면 어떻게해야합니까? 예를 들어, imagen2? i는 초보자이기 때문에 나는 코드를 알아낼 수 없다. 나는 조사를했고 couldnt는 이런 것을 찾았다. 도움이

File toFile = new File(rutadestino); 
if (toFile.exists()) { 
    // rename file 
    toFile.renameTo(new File("newFilePath/newName.jpg")); 
} else { 
    // do something if file does NOT exist 
} 

희망 : 사전 :

+0

Uhmwait, 왜 당신은'File' 객체를 통해 가고 있습니까? 'Path'를 직접 만들고 싶다면'Paths.get()'을 사용하십시오. – fge

+0

'if'와'exists()'를 사용 해본 적이 있습니까? 여기에서 읽을 수 있습니다 : http://www.tutorialspoint.com/java/io/file_exists.htm. 그것은 당신의 문제를 해결할 수 있습니다. – ViRALiC

+0

@fge mmm ok! 그게 나에게 코드를 저장하려고 : D 조. 정말 자바에 새로운, 그리고 자기 학습! 어쨌든, 나는 파일의 존재를 확인하는 방법을 계속 생각하고있다. 그렇다면 파일의 이름을 어떻게 바꾸는 지, 둘 다 같은 디렉토리에 저장할 수있다. 당신의 의견에 감사드립니다!! 죄송합니다, 내 영어, 아니 영어 스피커 : ( – neopablo2000

답변

3

의 덕분에 나는이 링크가 경우에 따라서 How do I check if a file exists?

도움이 될 것입니다 생각, 아마 그런 짓을! src은 복사 할 파일에 Path, dst 당신이 쓰고 싶은 파일에 대한 PathnewNamePath 경우 더 많은 정보를 위해, 또한 File

+0

sooo 매우 대단히 감사합니다 !! 지금 그것을 시험해 보라! !!! – neopablo2000

+0

어, OP는 Java 7을 사용합니다 ...'Files.exists()'가 있습니다. 무엇보다'File'의'.exists()'가 깨졌습니다 ('file.encoding'을 고려하지 않았습니다). – fge

+0

@fge allright, sooo ... 코드하는 법 알아보기 xD – neopablo2000

4

확인을위한 자바 문서를 확인, 여기에 빠른 해결책이다 당신이 당신의 경로 구축을 용이하게하기 위해 Path의 방법을 사용할 수 있습니다

if (Files.exists(dst)) 
    Files.move(dst, newName); 
Files.copy(src, dst); 

참고 : .resolve(), .resolveSibling(), .relativize() 파일에 당신은에 이름을 바꿀.


편집 :

private static Path findFileName(final Path dir, final String baseName, 
    final String extension) 
{ 
    Path ret = Paths.get(dir, String.format("%s.%s", baseName, extension)); 
    if (!Files.exists(ret)) 
     return ret; 

    for (int i = 0; i < Integer.MAX_VALUE; i++) { 
     ret = Paths.get(dir, String.format("%s%d.%s", baseName, i, extension)); 
     if (!Files.exists(ret)) 
      return ret; 
    } 
    throw new IllegalStateException("What the..."); 
} 
+0

상자에서 일했는데, 정말 고마워요 !! ;-). 내 호기심에 먹이를 한 번만 더 질문. 거기에 사이클 에서이 방법을 사용할 수있는 방법이 있나요? 즉, imagen.jpg가있는 경우 이름을 imagen2.jpg로 변경하고 imagen2.jpg가 있으면 imagen3.jpg 등으로 이름을 바꿉니다. fge .. 시간을 허리를 두는 것에 대해 유감스럽게 생각하고, 대단히 감사합니다. 나는 내 질문에 대해 광범위하게 대답 할 수 있습니다. :) – neopablo2000

+0

ViRALiC와 trentmwillis가 어쩌면 바보 같고 초짜 질문에 대답 해 주셔서 감사합니다. :) 그러나 나는 오늘 많이 배웠다! 그리고 나는 더 배울 것이 많다! 그러나 당신 같은 사람들은 우리에게 훨씬 더 쉽게이 길을 만듭니다 (클래스가 아닙니다 ;-))! 좋은 일을 계속 지켜라! – neopablo2000

+0

for 루프에서는 다른 이름을 테스트해야합니다. 해결책을위한 편집을보십시오 – fge

0

sory : 여기 디렉토리 (dir), 기본 파일 이름 baseName과 (점 제외)에 "확장"을 주어 적절한 이름 extension을 반환하는 기능입니다 늦은. 하지만 내 코드는 약간의 실수를하는 데 도움이 될 수 있습니다.

public void copyFile(File source, File dest) throws IOException, 
FileAlreadyExistsException { 
    File[] children = source.listFiles(); 
    if (children != null) { 
     for (File child : children) { 
      if (child.isFile() && !child.isHidden()) { 

       String lastEks = child.getName().toString(); 
       StringBuilder b = new StringBuilder(lastEks); 
       File temp = new File(dest.toString() + "\\" 
         + child.getName().toString()); 

       if (child.getName().contains(".")) { 
        if (temp.exists()) { 
         temp = new File(dest.toString() 
           + "\\" 
           + b.replace(lastEks.lastIndexOf("."), 
             lastEks.lastIndexOf("."), " (1)") 
             .toString()); 
        } else { 
         temp = new File(dest.toString() + "\\" 
           + child.getName().toString()); 
        } 
        b = new StringBuilder(temp.toString()); 
       } else { 
        temp = new File(dest.toString() + "\\" 
          + child.getName()); 
       } 
       if (temp.exists()) { 
        for (int x = 1; temp.exists(); x++) { 
         if (child.getName().contains(".")) { 
          temp = new File(b.replace(
            temp.toString().lastIndexOf(" "), 
            temp.toString().lastIndexOf("."), 
            " (" + x + ")").toString()); 
         } else { 
          temp = new File(dest.toString() + "\\" 
            + child.getName() + " (" + x + ")"); 
         } 
        } 
        Files.copy(child.toPath(), temp.toPath()); 
       } else { 
        Files.copy(child.toPath(), temp.toPath()); 
       } 
      } else if (child.isDirectory()) { 
       copyFile(child, dest); 
      } 
     } 
    } 
} 

특징 : 1. 파일이 대상에 존재하면 이름을 바꿉니다. 예 : document.doc (있는 경우) document (1) .doc (있는 경우) document (2) .doc (있는 경우) ... 2. 원본 (파일 만)에서 대상의 한 폴더로 모든 파일 복사